SimpleXML is an easy way of getting an element's attributes and text, if you know the XML document's layout. Compared to DOM or the Expat parser, SimpleXML just takes a few lines of code to read text data from an element.
The SimpleXML extension provides a very simple and easily usable toolset to convert XML to an object like this.
- Elements are converted to single attributes of the SimpleXMLElement object. When there's more than one element on one level, they're placed inside an array.
- Attributes are accessed using associative arrays, where an index corresponds to the attribute name.
- Element Data, text data from elements are converted to strings. If an element has more than one text node, they will be arranged in the order they are found.
SimpleXML is fast and easy to use when performing basic tasks such as reading xml file, extracting data from xml string and editing text node. However, when dealing with advanced XML, like namespaces, you are better off using the Expat parser or the XML DOM.
Let’s have an example how to read xml file using with SimpleXML in PHP.
Let’s create an XML file.
<?xml version="1.0" encoding="ISO-8859-1"?>
<to> Amit </to>
<from> Arun </from>
<subject> XML Parser</subject>
<message> This is testing message on PHP XML parser</message>
Now save it as ‘TestXML.xml’.
// load xml file with specified location
//get the name of the first element
$name = $loadXml->getName();
echo 'First element of file : '.$name."</br>";
// display the child element
foreach ($loadXml->children() as $child)
echo '<b>'.$child->getName().'</b>'." : ".$child ;