In the last tutorial, I gave an introduction to XML parsers in PHP and let us recollect key information from that. SimpleXML parser,
Apart from the above, the PHP SimpleXML parser is capable of working via both procedural and object-oriented styles to parse an XML document.
simplexml_load_file(($fileName,$class,$options,$ns,$is_prefix);
simplexml_load_string($XMLData,$class,$options,$ns,$is_prefix);
3. simplexml_import_dom()
simplexml_load_string($DOMNode,$class);
SimpleXML parser extension includes classes,
Both of the above classes include several properties to access XML nodes while parsing. For example, we can
SimpleXMLIterator inherits SimpleXMLElement class to implement a RecursiveIterator to perform recursive parsing on XML nodes.
Now, it’s time to experiment with the above SimpleXML functions to parse an XML document. First, we should create an XML document. Let us take a simple XML document,
<?xml version="1.0"?>
<toys>
<toy>
<name>Ben 10 Watch</name>
<type>Battery Toys</type>
</toy>
<toy>
<name>Angry Birds Gun</name>
<type>Mechanical Toys</type>
</toy>
</toys>
We can directly load this XML using simplexml_load_string(). Otherwise, we can save this file as toys.xml and send it for simplexml_load_file()
<?php
$xml = simplexml_load_file("../toys.xml");
print "<PRE>";
print_r($xml);
print "</PRE>";
?>
As a result, the SimpleXMLElement object will be returned as,
SimpleXMLElement Object(
[toy] => Array(
[0] => SimpleXMLElement Object(
[name] => Ben 10 Watch
[type] => Battery Toys
)
[1] => SimpleXMLElement Object(
[name] => Angry Birds Gun
[type] => Mechanical Toys
)
)
)
To add a child element to a node in a XML document, we use addChild() of SimpleXMLElement class.
<?php
$xmlDocument = '<?xml version="1.0"?>
<toys xmlns:h="http://www.w3.org/TR/html4/">
<toy>
<name>Ben 10 Watch</name>
<type>Battery Toys</type>
</toy>
<toy>
<name>Angry Birds Gun</name>
<type>Mechanical Toys</type>
</toy>
</toys>';
$xml = new SimpleXMLElement($xmlDocument);
$toy = $xml->addChild('toy');
$toy->addChild('name', 'Remote Control Car');
$toy->addChild('type', 'Remote Control Toys');
print "<PRE>";
print_r($xml);
print "</PRE>";
?>
Download PHP SimpleXML Parser Source Code