How to parse xml in php [Explained with code]

  1. Previous
  2. Next
  3. Recent

    1. Signs 'He' May be Cheating on You
    2. 7 Vows of Hindu Marriage - Know What 'Saat Vachans' Mean
    3. RuPay vs Visa vs Mastercard vs American Express- A Comparison
    4. What is RuPay? Everything You Need to Know About India's Domestic Payment System!
    5. Top 10 Online Portals to Find a High Paying Job in India
    6. Top Indians who Revolutionized the IT Sector in India
    7. 8 Initiatives by Narendra Modi that Could Change the Future of the Nation
    8. 8 Work-from-home Jobs for Housewives, Students, and Part timers
    9. Complete Company Registration Process in India - Explained
    10. Change Name in India in 5 Steps - Filing Affidavit, Newspaper Ad & Gazette Notification

In our previous tutorial, we explained about converting database records to XML. This post is a continuation of it wherein we’ll parse the generated xml file and retrieve data from it.

Parsing XML is easy by using the two functions provided by SimpleXMLElement php class.

After we parse the XML file, we can save data to database or use it wherever we want.

Here is the XML file ‘myxml1.php’ that we’ll parse,

parse xml file using php

PHP code for parsing XML


<?php

$parse_xml = simplexml_load_file("myxml1.xml");
$root=$parse_xml->getName();

echo "<div style='font-family:Tahoma;font-size:12px;'><strong>These are the ".$root . " with id and level names: </strong><br /><br />";

foreach($parse_xml->children() as $child)
 {
echo "<p style='margin-left:20px;border-left:2px solid orange;padding:5px;font-family:Tahoma;font-size:12px;'>";
 foreach($child->children() as $subchild)
 {
 echo $subchild->getName() . ": " . $subchild . "<br />";
 }
echo "</p></div>";
 }

?>

  1. First we load the XML file ‘myxml1.xml’ for parsing and save in variable $prase_xml as string.
  2. Next we call getName() function of SimpleXMLElement php class to get the name of root element.
  3. Then we call the children() function to loop through the child and sub-child nodes of the loaded XML file.
  4. We add some styling to our parsed XML data. Here is how it’ll look like after executing the above php code,

    parse xml using php code

blog comments powered by Disqus