XML Parsing using simplexml_load_file in PHP

In this article, I will share about parsing XML using php script. On this occasion, the function used is simplexml_load_file. simplexml_load_file is a class that is already contained in the PHP version 5 and later. First, we first create a file with the extension .xml.  You can see an example of a script xml like this:
 filename: books.xml

<books>
  <book id="1">
    <title>Learning PHP, MySQL, JavaScript, CSS &amp; HTML5 A Step-by-Step Guide to Creating Dynamic Websites</title>
    <author>Robin Nixon</author>
    <isbn>1491949465</isbn>
    <publisher>O'Reilly Media</publisher>
    <image>http://ecx.images-amazon.com/images/I/51AkW1znNmL._SL210_.jpg</image>
    <url>http://astore.amazon.com/freeeboodow07-20/detail/1491949465</url>
  </book>
  <book id="2">
    <title>PHP and MySQL Web Development (4th Edition)</title>
    <author>Luke Welling, Laura Thomson</author>
    <isbn>9780672329166</isbn>
    <publisher>Addison-Wesley Professional</publisher>
    <image>http://ecx.images-amazon.com/images/I/51AigeIv7OL._SL210_.jpg</image>
    <url>http://astore.amazon.com/freeeboodow07-20/detail/0672329166</url>
  </book>
  <book id="3">
    <title>PHP and MySQL for Beginners</title>
    <author>Mark A Lassoff</author>
    <isbn>0990402010</isbn>
    <publisher>LearnToProgram, Incorporated</publisher>
    <image>http://ecx.images-amazon.com/images/I/51wWpAP-XRL._SL210_.jpg</image>
    <url>http://astore.amazon.com/freeeboodow07-20/detail/0990402010</url>
  </book>
  <book id="4">
    <title>PHP Cookbook: Solutions &amp; Examples for PHP Programmers</title>
    <author>David Sklar, Adam Trachtenberg</author>
    <isbn>144936375X</isbn>
    <publisher>Addison-Wesley Professional</publisher>
    <image>http://ecx.images-amazon.com/images/I/51xoxfU7GxL._SL210_.jpg</image>
    <url>http://astore.amazon.com/freeeboodow07-20/detail/144936375X</url>
  </book>
</books>

After the code you create, saved with the file name books.xml, on your local server. Next we create the php code like this:

filename: parsing.php

<?
$file="books.xml";
$xml=simplexml_load_file($file);
echo "<h1>".$xml->getName()."</h1>";
foreach($xml->children() as $child){
  echo $child->attributes()->id.".<br>";
  echo "<img src=\"".$child->children()->image."\" /><br>";
  echo $child->children()->title."<br>";
  echo "By : ".$child->children()->author."<br>";
  echo "ISBN : ".$child->children()->isbn."<br>";
  echo "Publisher : ".$child->children()->publisher."<br>";
  echo "<a href=\"".$child->children()->url."\" target=\"_blank\"><b>Buy</b></a><br>";
  echo "<hr/>";
}
?>

Save the code as parsing.php, then run the file parsing.php on your local server.

download code