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]

Now we need to open this file in PHP.

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

Step 3 : Accessing the Node Data

When we need to access the node data then we can use following syntax in the nested loop.

Step 4 : Accessing the Attribute Data

Suppose we need to access the attribute value of <Student> then we can use following syntax.

Combining the Code :

Output :

To learn more about PHP you can visit our PHP tutorials home page.