Latest web development tutorials

PHP XML SimpleXML

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.


installation

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"?>
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>

Now we want to output different information above XML file:

Example 1

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

<?php
$xml=simplexml_load_file("note.xml");
print_r($xml);
?>

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:

<?php
$xml=simplexml_load_file("note.xml");
echo $xml->to . "<br>";
echo $xml->from . "<br>";
echo $xml->heading . "<br>";
echo $xml->body;
?>

Running instance »

The code above will output:

Tove
Jani
Reminder
Don't forget me this weekend!

Example 3

Output element names and data of each sub-node:

<?php
$xml=simplexml_load_file("note.xml");
echo $xml->getName() . "<br>";

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

Running instance »

The code above will output:

note
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 .