Latest web development tutorials


PHP SimpleXML most common XML processing tasks remaining tasks referred to the other expansion process.

What is PHP SimpleXML?

SimpleXML is new in PHP 5 features.

SimpleXML extension provides an easy way to get the name of the XML elements and text.

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

SimpleXML can be an XML document (or XML string) into an object, such as:

  • Elements are converted to a single attribute SimpleXMLElement object. When there are multiple elements on the same level, they will be placed in the array.
  • Properties by using associative array access, which corresponds to the index attribute name.
  • Elements inside the text is converted to a string. If an element has multiple text node, the order in which they were found in order.

When performing basic tasks similar to the following, SimpleXML use very fast:

  • Read / extract data XML file / string
  • Editing text nodes or attributes

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


Starting from PHP 5, SimpleXML functions are part of the PHP core. No installation needed to use these functions.

PHP SimpleXML examples

Suppose we have the following XML document, " note.xml ":

<?xml version="1.0" encoding="ISO-8859-1"?>
<body>Don't forget me this weekend!</body>

Now we want to output different information above XML file:

Example 1

$ Xml output variable (an object is SimpleXMLElement) keys and elements:


Running instance »

The code above will output:

SimpleXMLElement Object ( [to] => Tove [from] => Jani [heading] => Reminder [body] => Don't forget me this weekend! )

Example 2

Each element in the output XML file data:

echo $xml->to . "<br>";
echo $xml->from . "<br>";
echo $xml->heading . "<br>";
echo $xml->body;

Running instance »

The code above will output:

Don't forget me this weekend!

Example 3

Output element names and data of each sub-node:

echo $xml->getName() . "<br>";

foreach($xml->children() as $child)
echo $child->getName() . ": " . $child . "<br>";

Running instance »

The code above will output:

to: Tove
from: Jani
heading: Reminder
body: Don't forget me this weekend!

More information PHP SimpleXML

For more information about PHP SimpleXML functions, visit our PHP SimpleXML reference manual .