Read XML file using PHP
In this tutorial we will be learning the the way to read and parse XML file using PHP. We have single XML file and we need to open that file for reading the XML nodes and attributes.
Step 1 : Read from a XML File :
Consider that we have XML file. Say student.xml. [Learn XML Here]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
<?xml version="1.0"?> <StudentsList> <Students> <Student roll="B1"> <sname>Sam</sname> <marks>90</marks> </Student> </Students> <Students> <Student roll="C1"> <sname>Ronaldo</sname> <marks>67</marks> </Student> </Students> </StudentsList> |
Now we need to open this file in PHP.
1 2 3 4 |
<?php $xml = simplexml_load_file("student.xml") or die("Error: Cannot create object"); ?> |
We need to use the above line of code for loading the XML file. simplexml_load_file() will interprets an XML file into an object
Step 2 : Read from a XML File :
Using the outer loop we are iterating over all the <Students> nodes. Now we are selecting the individual <Student> node from outer <Students> node
1 2 3 4 |
<?php foreach($xml->children() as $Students){ foreach($Students->children() as $Student => $data){ ?> |
Step 3 : Accessing the Node Data
When we need to access the node data then we can use following syntax in the nested loop.
1 2 3 4 |
<?php echo $data->sname; echo $data->marks"; ?> |
Step 4 : Accessing the Attribute Data
Suppose we need to access the attribute value of <Student> then we can use following syntax.
1 2 3 |
<?php echo $data['roll']; ?> |
Combining the Code :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
<!DOCTYPE html> <html> <body> <?php $xml = simplexml_load_file("student.xml") or die("Error: Cannot create object"); foreach($xml->children() as $Students){ foreach($Students->children() as $Student => $data){ echo $data['roll']. "<br />"; echo $data->sname . "<br />"; echo $data->marks . "<br />"; echo "<br />"; } } ?> </body> </html> |
Output :
1 2 3 4 5 6 7 |
B1 Sam 90 C1 Ronaldo 67 |
To learn more about PHP you can visit our PHP tutorials home page.