SimpleXML
SimpleXML converts the XML document into 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 like:
* Reading XML files
* Extracting data from XML strings
* Editing text nodes or attributes
However, when dealing with advanced XML, like namespaces, you are better off using the Expat parser or the XML DOM.
Let a xml file is:
<?xml version="1.0" encoding="ISO-8859-1"?>
<note>
<name>Janakiranjan</name>
<from>India</from>
<work>Software Developer</work>
<site>themysolutions.in</site>
</note>
We want to output the element names and data from the XML file above.
Here`s what to do:
1. Load the XML file
2. Get the name of the first element
3. Create a loop that will trigger on each child node, using the children() function
4. Output the element name and data for each child node
<?php
$xml = simplexml_load_file("test.xml");
echo $xml->getName() . "<br />";
foreach($xml->children() as $child)
{
echo $child->getName() . ": " . $child . "<br />";
}
?>
XML DOM
Example of My.xml:
<?xml version="1.0" encoding="ISO-8859-1"?>
<questions>
<quest>
<id>1</id>
<text>mathematics</text>
</quest>
</questions>
$doc = new DOMDocument();
$doc->load("my.xml");
$questions = $doc->getElementsByTagName( "quest" );
foreach($questions as $item)
{
$ID =$item->getElementsByTagName("id")->item(0)->nodeValue;
$text=$item->getElementsByTagName("text")->item(0)->nodeValue;
echo $ID."=>".$text."<br/>";
}
The Output is:
1=>mathematics