What is XML
XML refers to eXtensible Markup Language. The reason XML is called an eXtensible Markup language is that it allows you to define your own element and tag.
The main purpose of XML is to allow sharing of data. In this tutorial i am using SimpleXML to read the XML file.
I am using my XML file name as blog.xml.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
<articles> <article published="2012-03-04 13:10:26"> <title>Online Education</title> <author>Hudson</author> </article> <article published="2013-07-14 16:27:42"> <title>Popular Personality</title> <author>Emma</author> </article> <article published="2013-07-23 11:23:50"> <title>Popular Movies</title> <author>Jhon</author> </article> </articles> |
Note – In XML everything is case sensitive. so article and Article both are different thing.
How to Read XML File in PHP Using SimpleXML
To use simpleXML call simplexml_load_file() function , pass file name. It interprets the XML file and converts into an object.Then you can access object properties using standard Object notation.
NOTE: SimpleXML library is available in PHP5 or higher. If you are using older version of PHP then it will not work.
1 2 3 4 5 6 7 8 9 |
<?php // Read blog.xml file $xml = simplexml_load_file("blog.xml"); // Print echo '<pre>'; print_r($xml); ?> |
If your print $xml, it will print the object format.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
SimpleXMLElement Object ( [article] => Array ( [0] => SimpleXMLElement Object ( [@attributes] => Array ( [published] => 2012-03-04 13:10:26 ) [title] => Online Education [author] => Hudson ) [1] => SimpleXMLElement Object ( [@attributes] => Array ( [published] => 2013-07-14 16:27:42 ) [title] => Popular Personality [author] => Emma ) [2] => SimpleXMLElement Object ( [@attributes] => Array ( [published] => 2013-07-23 11:23:50 ) [title] => Popular Movies [author] => Jhon ) ) ) |
SimpleXML handles element attributes transparently. Attributes-value pairs are represented as members of PHP associative array and can be accessed like regular array elements. In this xml published is an attribute.
Now you can process the object in you PHP file, pick and format the contents as per your requirement.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
// Process XML <?php $xml = simplexml_load_file("blog.xml"); foreach ($xml as $xml_data){ $title=$xml_data->title; $author=$xml_data->author; $date=$xml_data['published']; // Attribute echo "<li> Post $title is written by $author on $date</li>"; } ?> |
Conclusion
Parsing XML file through SimpleXML is very simple to use. If you’r looking for object-oriented approach you can check SimpleXMLElement class. If you have any suggestion for an improvement, you are most welcome.