PHP SimpleXML Parser

PHP SimpleXML Parser

The SimpleXML extension is the easiest and most popular way to read XML data in PHP. It is a tree-based parser that converts an XML document into an easily accessible PHP Object.

If your XML file isn't massively huge, SimpleXML is the best tool for the job.


Reading XML from a String

The simplexml_load_string() function is used to read XML data directly from a text string. It returns an object containing the parsed data.

Let's create a simple XML string representing a note, and use SimpleXML to parse it!

SimpleXML String Example

<?php
$myXMLData = "<?xml version='1.0' encoding='UTF-8'?>
<note>
  <to>Tove</to>
  <from>Jani</from>
  <heading>Reminder</heading>
  <body>Don't forget me this weekend!</body>
</note>";

// Convert the string into an object $xml = simplexml_load_string($myXMLData) or die("Error: Cannot create object");

// Output the parsed object print_r($xml); ?>

Reading XML from a File

If your XML data is stored in an actual file (like data.xml), you can use the simplexml_load_file() function instead.

<?php
// Load the file directly
$xml = simplexml_load_file("note.xml") or die("Error: Cannot create object");
print_r($xml);
?>

In both cases, you will notice that the print_r() function outputs a beautifully structured SimpleXMLElement object. In the next chapter, we will learn how to extract specific data values from this object.


Exercise

?

Which function is used to parse XML data stored within a PHP text string?