PHP SimpleXML
SimpleXML is a new feature of PHP which has been included in PHP 5, it similar to DOM and Expat but simpler than these parsers.
SimpleXML converts the elements and attributes of XML in a very easy way:
Elements are changed over to single attributes of the SimpleXMLElement object. If there is more than one element is present in one level then they've placed inside an array.
Associative arrays are used to access attributes, where an index is used to point attribute name.
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 appear.
- SimpleXML is preferable in basic tasks like:
- Reading XML files
- Extracting data from XML strings.
- Editing text nodes
Now let's us consider a xml file named MyFirst.xml is present in our current project directory. The content of the file is as follows:
<?xml version="1.0" encoding="ISO-8859-1" ?>
<lang>
<php>
PHP is very easy to learn
</php>
<Java>
Java is the king of open source language
</Java>
</lang>
Now to access the element of this file we need to write php coding as follows, in a .php file:
<?php
$var=simplexml_load_file("MyFirst.xml");
echo $var->getName()."<br/>";
foreach($var->children() as $child)
{
echo $child->getName()." ->".$child."<br/>";
}
?>
Output will be:
lang
php -> PHP is very easy to learn
Java -> Java is the king of open source language