PHP SimpleXML

SimpleXML handles the most common XML tasks, and other tasks are handled by other extensions.

What is SimpleXML?

SimpleXML is a new feature in PHP 5. It is a convenient way to obtain element attributes and text when you understand the layout of the XML document.

Compared to DOM or Expat parser, SimpleXML can read text data from elements with just a few lines of code.

SimpleXML can convert an XML document into an object, such as:

  • Element - a single attribute converted to a SimpleXMLElement object. When multiple elements exist at the same level, they are placed in an array.
  • Attributes - accessed through an associative array, where the index corresponds to the attribute name.
  • Element data - the text data from the element is converted to a string. If an element has multiple text nodes, they are arranged in the order they are found.

SimpleXML is very quick to use when performing basic tasks like the following:

  • Read an XML file
  • Extract data from an XML string
  • Edit text nodes or attributes

However, when dealing with advanced XML, such as namespaces, it is best to use the Expat parser or XML DOM.

Installation

Starting from PHP 5.0, the SimpleXML function is a part of the PHP core. These functions can be used without installation.

Using SimpleXML

Below is an XML file:

<?xml version="1.0" encoding="ISO-8859-1"?>
<note>
<to>George</to>
<from>John</from>
<heading>Reminder</heading>
<body>Don't forget the meeting!</body>
</note>

We plan to output the element name and data from the above XML file.

This is what needs to be done:

  1. Load XML file
  2. Get the name of the first element
  3. Use the children() function to create a loop triggered at each child node
  4. Output the element name and data of each child node

Example

<?php
$xml = simplexml_load_file("test.xml");
echo $xml->getName() . "<br />";
foreach($xml->children() as $child)
  {
  echo $child->getName() . ": " . $child . "<br />";
  }
?>

The output of the above code:

note
to: George
from: John
heading: Reminder
body: Don't forget the meeting!

More information about PHP SimpleXML

For more information about PHP SimpleXML, please visit our PHP SimpleXML Reference Manual.