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

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.
Tutorial
Introduction
Installation
Syntax
Variable
Superglobals
Data Types
String
Array
Multidimensional Array
Sort Array
Constant
Operators
Cookies
Sessions
DateTime
Error Handling
Exception Handling
File
Write and Create File
File Open, Read and Close
File Upload
Filtering
Redirecting
Advanced Filters
Forms
Form Required Field
Validate Email/URL
Form Validation
Form Action
Function
Prepared Statements
JSON
Calendar
ZIP File
FTP
HTTP Response
DateTime Functions
Error Functions
File Function
Filter
Math Functions
Mail Function
Miscellaneous Functions
Date Format
String Functions
Array Functions
Directory Functions
MySQL Database
MySQL Connection
MySQL Create Database
MySQL Create Table
MySQL Delete Data
MySQL Insert Data
MySQL Get Last Record ID
MySQL Insert Multiple Records
MySQL Select Data
MySQL Limit Data
MySQL Update Data
MySQLi Functions
AJAX and MySQL
AJAX Search
AJAX Poll
RSS Reader
Read XML File in PHP
XML Parser
SimpleXML Parser
SimpleXML: Node and Attribute
Expat XML Parser
DOMDocument
Libxml Functions
SimpleXML Functions
XML Parsing Functions
PHP isset
PHP echo and print
PHP if else and elseif
PHP switch case
PHP include File
PHP while Loop
PHP for and foreach
PHP mail()
PHP explode()
PHP substr()
PHP str_replace()
PHP array_push
PHP count()