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:
$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:
<?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:
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:
<?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:
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
- 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
- Free certificates of completion
- Focused on data science skills
- Flexible learning timetable
- Simplistic design (no unnecessary information)
- High-quality courses (even the free ones)
- Variety of features
- Nanodegree programs
- Suitable for enterprises
- Paid Certificates of completion
- A wide range of learning programs
- University-level courses
- Easy to navigate
- Verified certificates
- Free learning track available
- University-level courses
- Suitable for enterprises
- Verified certificates of completion
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:
<?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:
<?php
$xml = simplexml_load_file("file.xml") or die("Failed to create object");
print_r($xml);
?>
This is the SimpleXMLElement we get displayed:
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.