Use of SimpleXML in PHP
In this article I am going to explain how to use SimpleXML in PHP.
PHP Version 5 introduces SimpleXML and is a part of the PHP core. SimpleXML is a PHP extension to easily manipulate or use XML data. SimpleXML works like a DOM, with objects, takes all the XML documents as a hierarchical tree, but unlike the DOM, SimpleXML is more flexible and uses less memory because the XML elements are stored directly as a PHP variable. If we say it in other words, "A SimpleXML is an extension that simplifies the parsing and processing of an XML document.".
SimpleXML converts the XML document into an object, decribed in the folllowing.
Elements are converted to single attributes of the SimpleXMlElement. If in the one level, there is a more than one element, they are placed inside an array.
Text data from elements are converted to a string.
Attributes are accessed using an associative array.
Why we use SimpleXML:
- It easy to use.
- You do not need to use DOM extensions.
- In this we can directly jump to content by providing the tag name.
- Reading XML document with SimpleXML
First, the XML content must be loaded and converted to an object, with one of the following functions.
It is used when the XML content is an external file.
It is used when the XML content is a string.
The SimpleXMLElement object has three methods.
This method will return the list of child nodes and this method works with a foreach loop.
for(xml_object->children() as $variablename)
This method will return the name of the xmltag.
This method will return the list of attributes and values that the XML node has. This method will work along with a foreach loop.
foreach(xml_object->current_position_node->attributes() as $attributeName=> $attributevalue)
Example of SimpleXML In PHP
To use a SimpleXml in PHP, use the following steps:
First, create a XML file as in the following:
<InterviewDate>12 to 15 Dec-2012</InterviewDate>
Note: Save it as Filename.xml (like simplexml.xml) and if you are using Wamp server to run PHP projects with SimpleXML then the php_xsl extension must be included. To include the php_xsl extension, click on the Wamp server Icon then "PHP" -> "PHP Extensions" -> "php_xsl".
Then create a PHP file.
Here is what to do:
Load an XML file.
Get the name of the first element.
Create a loop that will trigger on each child node, using children().
Output the element name and data for each child node.
echo $xml->getName() . "<br>";
foreach($xml->children() as $child)
echo $child->getName() . ": " . $child . "<br>";
The output of the above code will look like: