Monday 7 April 2014

Reading XML file - PHP

 

The easiest and simplest way to read XML file is using SimpleXML.

 

We'll consider a simple XML file test.xml with the following nodes and values.


<!-- Test.xml --> 
<root>
   <node1>Hello</node1>
   <node2>World</node2>
    <node3>This is simple Example of Parsing XML files </node3>
<root>  
 


 Loading a XML file

$xml=simplexml_load_file("filename");

Parsing a Node value 

$node=$xml->node_name;
  

 Example to demonstrate the usage of simpleXML


<?php
$xml=simplexml_load_file("test.xml");
echo $xml ->node3;
 echo '<br/>';
foreach($xml->children() as $child)   // children() get all the child nodes in the XML file.
{
      echo 'Node_name: '.$child ->getName().'   ';      // displays the node_name.
     echo 'Node_value: '.$child.'<br/>';   // displays the node value.
}
?>  




Output will be displayed as follows


This is a simple example of parsing XML files
Node_name: node1 Node_value: Hello
Node_name: node2 Node_value: World
Node_name: node3 Node_value: This is a simple example of parsing XML files 











Nodes having nested nodes can be parsed using the above method by using foreach loop. 

for more Details refer
  1. http://www.w3schools.com/php/php_xml_simplexml.asp 
  2. http://www.php.net/manual/en/simplexml.examples-basic.php  
  3. http://www.php.net/manual/en/ref.xml.php 

No comments:

Post a Comment