🔥 $100K Hit! Where Will Bitcoin Go Next? Find Out Live!

Code has been added to clipboard!

How to Read XML Files: Getting Node & Attribute Values in XML Parsing

Reading time 4 min
Published Aug 8, 2017
Updated Oct 15, 2019

By now, you understand what a PHP parser is, and how to read XML files using them. You also learned about SimpleXML parser more closely. In this tutorial, we will deepen your knowledge about SimpleXML and how to read XML files successfully.

A tree structure of a document consists of nodes. Following the tree metaphor, you could call them branches. An element is a type of node. So is an attribute, which is not considered to be a child of an element, though it does hold information about it. This data is contained in quotes, which makes it a string.

By using PHP XML code examples, we will show you how to get the values of nodes and attributes. To do that, we will be using PHP simplexml_load_file() function.

How to Read XML Files: Main Tips

  • SimpleXML is a tree-based parser. The tree data structure is made out of nodes.
  • You can access Node and Attribute values using SimpleXML.
  • To do that, you have to understand the usage of PHP simplexml_load_file function.

Example of XML File

Let's have a look at one of our XML documents, which is called bookstore.xml. You will see it has three categories of books listed. Each category has one book in it, and the information on a particular book consists of its name, author, price, language and year of release:

Example
<?xml version="1.0" encoding="utf-8"?>
<books>
  <book category="COOK">
    <name lang="en">The Silver Spoon</name>
    <by>Cielia D`Onofrio</by>
    <released>1950</released>
    <pricing>35.00</pricing>
  </book>
  <book category="FANTASY">
    <name lang="en">The Fellowship of the Ring</name>
    <by>J.R.R. Tolkien</by>
    <released>1954</released>
    <pricing>39.99</pricing>
  </book>
  <book category="TECH">
    <name lang="en-us">Think like a programmer</name>
    <by>V. Anton Spraul</by>
    <released>2012</released>
    <pricing>39.99</pricing>
  </book>
</books>

Analyze it carefully as we will use this file to explain how to read XML files.

Retrieve Node Value from a Specific Element

Imagine we need to make our code written in PHP read the XML example we introduced in the previous section. Let's say we want to return the titles of the first two books. The code you see below acquires the values of <name> elements of the books we need from the books.xml file:

Example
<?php
  $xml = simplexml_load_file('bookstore.xml') or die('Failed to create an object');
  echo $xml->book[0]->name . "<br>";
  echo $xml->book[1]->name; 
?>

After this PHP XML code is executed, we get the names of the first two books outputted like this:
The Silver Spoon
The Fellowship of the Ring

DataCamp
Pros
  • Easy to use with a learn-by-doing approach
  • Offers quality content
  • Gamified in-browser coding experience
  • The price matches the quality
  • Suitable for learners ranging from beginner to advanced
Main Features
  • Free certificates of completion
  • Focused on data science skills
  • Flexible learning timetable
Udacity
Pros
  • Simplistic design (no unnecessary information)
  • High-quality courses (even the free ones)
  • Variety of features
Main Features
  • Nanodegree programs
  • Suitable for enterprises
  • Paid Certificates of completion
edX
Pros
  • A wide range of learning programs
  • University-level courses
  • Easy to navigate
  • Verified certificates
  • Free learning track available
Main Features
  • University-level courses
  • Suitable for enterprises
  • Verified certificates of completion

Looping to Get Values

Now, if we want to get the node value of each element, we can use loops. Let's see the code below. Basically, it iterates through every <book> element in our XML document, getting the node value of each element:

Example
<?php
  $xml = simplexml_load_file('bookstore.xml') or die('Failed to create an object');
  foreach($xml->children() as $books) {       	
    echo $books->name . ", ";     
    echo $books->by . ", ";     
    echo $books->released . ", ";      	
    echo $books->pricing . "<br>";
  }
?>

This is the output we get after the code is done running:
The Silver Spoon, Cielia D'Onofrio, 1950, 35.00
The Fellowship of the Ring, J.R.R. Tolkien, 1954, 39.99
Think like a programmer, V. Anton Spraul, 2012, 39.99

Specific Attribute Values

Now, let's try something more complex. The code example you can see below will acquire the category attribute value from the first <book> element it finds. Then, it will retrieve the lang attribute's value from the <name> element from the second <book> element:

Example
<?php
  $xml = simplexml_load_file('bookstore.xml') or die('Failed to create an object');
  echo $xml->book[0]['category'] . "<br>";
  echo $xml->book[1]->name['lang']; 
?>

The output we get is the category of the first book and the language of the second:
COOK
en

Looping to Retrieve Attribute Values

The PHP XML example below shows the script that iterates through every <name> element in our books.xml file and gets their attribute values:

Example
<?php
  $xml = simplexml_load_file('bookstore.xml') or die('Failed to create an object');
  foreach($xml->children() as $books) {       	
    echo $books->name['lang'];    
    echo "<br>"; 
  }
?>

This is the output we get in this case:
en
en
en-us

How to Read XML Files: Summary

  • PHP SimpleXML extension allows the coder to PHP read XML documents, access and use them as data structures made of nodes.
  • It also allows getting Node and Attribute values. To do that, we use PHP simplexml_load_file function.