Code has been added to clipboard!

SimpleXML Parser: Make PHP Parse XML With Fewer Code Lines

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

To make PHP parse XML documents, you need to use parsers. There are multiple ways to make PHP parse XML data, and each is better suited for different cases.

SimpleXML is designed for managing and retrieving data from XML files. Once it is applied, SimpleXML organizes the content of an XML document so you could retrieve information on different elements and their attributes. You can even add new child elements to an element and count them.

As the name suggests, PHP SimpleXML is best-suited for small and XML files with a simple structure. Using huge documents might mess up its performance. However, if the file you wish to parse is small, SimpleXML will help you do that in fewer code lines than other parsers.

SimpleXML: Main Tips

  • PHP SimpleXML extension lets you access and work with XML data.
  • This parser is tree-based and provides an efficient method of getting the name of a specific element, attributes or text content. However, you have to be aware of the layout or structure of the XML document you're working with.
  • Using Simple XML, you can convert documents written in PHP XML to arrays or objects.
  • It takes fewer lines of code than its alternatives, Expat and DOM.
  • It's available on any server that has PHP installed.

Reading XML Data: String

Whenever our work requires PHP reading XML document data from string, we use a function called simplexml_load_string().

Imagine we have a variable $my_data that contains XML data. The following code example shows how it would look first declared:

Example
$my_data = 
"<?xml version='1.0' encoding='UTF-8'?>
<note>
<to>You</to>
<from>Me</from>
<heading>The Game</heading>
<body>You lost it.</body>
</note>";

Now, in the example below, simplexml_load_string() is used to PHP read XML data straight from previously mentioned variable:

Example
<?php
  $xml_data = "<?xml version='1.0' encoding='UTF-8'?>  
    <note>  
    <to>You</to>  
    <from>Me</from>  
    <heading>The Game</heading>  
    <body>You lost it.</body>  
    </note>";  
  $xml = simplexml_load_string($xml_data) or die('Failed to create object');
  print_r($xml);  
?>

Here is the output we get in XML:

Example
SimpleXMLElement Object ( [to] => You [from] => Me [heading] => The Game [body] => You lost it. )

To catch all the errors and then go through them while a PHP XML file is loading, you can use libxml functions. Look at the code example below. You can see that we are trying to load broken XML:

Example
<?php
  libxml_use_internal_errors(true);
  $my_data =
    "<?xml version='1.0' encoding='UTF-8'?> 
    <document> 
    <to>You</wrong>
    <from>Me</wrong>
    <heading>The Game</wrong>
    <body>You lost it</wrong>
    </document>"; 

  $xml = simplexml_load_string($my_data);
  if ($xml === false) {
    echo "Failed to load XML: ";
    foreach(libxml_get_errors() as $error) {
      echo "<br>", $error->message;
    }
  } else {
    print_r($xml);
  }
?>

Now, this is the output we would get in XML in such case:

Example
Failed loading XML: 
Opening and ending tag mismatch: to line 3 and wrong
Opening and ending tag mismatch: from line 4 and wrong
Opening and ending tag mismatch: heading line 5 and wrong
Opening and ending tag mismatch: body line 6 and wrong

Read from File

By using simplexml_load_file(), you can make PHP parse XML data from files. Imagine we are using an XML document simply called file.xml. In the example below, you can view its content:

Example
<?xml version="1.0" encoding="UTF-8"?>
<note>
  <to>You</to>
  <from>Me</from>
  <heading>The Game</heading>
  <body>You lost it.</body>
</note>

Now, let's see how simplexml_load_string() can be used to read data from an XML document:

Example
<?php  
  $xml = simplexml_load_file("file.xml") or die("Failed to create object");  	
  print_r($xml);  
?>

This is the SimpleXMLElement we get displayed:

Example
SimpleXMLElement Object ( [to] => You [from] => Me [heading] => The Game [body] => You lost it. )

SimpleXML: Summary

  • SimpleXML is a very convenient choice since it is inbuilt in PHP since version 5 and available in all PHP supporting servers.
  • It is a tree-based parser. Therefore, you need to understand the structure of the document you're going to parse. An element in an XML document is classed as SimpleXMLElement.
  • SimpleXML lets you treat XML files as usable data structures: you can easily fetch certain content, attributes or names of elements. Basically, it turns PHP XML into an array.
  • Compared to Expat or DOM parsers, it requires less code lines to PHP parse XML data properly.
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()