PHP MySQL tutorial

Reading XML Nodes/Attributes Values in PHP

In the previous article, we studied how we can read an XML documents in the form of string as well as in the form of a file. This article extends the previous one by explaining the process of reading XML node and attribute values. Let’s jump straight into a working example. Create a file named studentrecord.xml and copy the following xml data into it.



    
    Mike
    10
    Male
    City High School
    
    
    Annu
    12
    Male
    Delhi Public School
    
    
    Chen
    11
    Female
    China International School.
    

In the above code records of three students are being saved in an XML file. The outer most node is the studentrecord node which contains three student nodes which in turn contain multiple nodes to store information such as name, age, gender and school of the student. The student node also contains an attribute nationality, also the school node contains an attribute city.

Read Node Data

Now, to read the value of the Name element of all the student nodes, the following PHP code can be used.

Student[0]->Name . "
"; echo $xmlparser->Student[1]->Name . "
"; echo $xmlparser->Student[2]->Name; ?>

Download the code
Run the code

In the above code the studentrecord.xml file is being loaded into PHP environment via simplexml_load_file parser. Parent nodes are loaded into arrays in the form of objects. For instance if you want to access the first Student record, you will use Student[0], for second record you will write Student[1] and so on. Each element within a specific node can be accessed via a single arrow. For instance to access data of the Name element of second student the syntax used will be Student[1]->Name. The above example displays names of all the students in the studentrecord.xml files.

Reading attribute values.

In the studentrecord.xml file, the Student node contains “nationality” attribute, while the child School node also contains an attribute “city”. The following PHP script is used to read values of these attributes.


Student[0]['nationality'] . "
"; echo $xmlparser->Student[1]->School['city'] . "
"; ?>

Download the code
Run the code

The above code will print the value of nationality attribute of the first School node, and it will also print the value of the city attribute of the School element of the second Student node.

<<< Reading XML data in PHPXML DOM Parser >>>
Copyright 2005-2016 KnowledgeHills. Privacy Policy. Contact .