PHP SimpleXML
PHP SimpleXML handles the most common XML tasks, while other tasks are left to other extensions.
What is PHP SimpleXML?
SimpleXML is a new feature in PHP 5.
The SimpleXML extension provides a simple way to get the names and text of XML elements.
Compared to the DOM or Expat parsers, SimpleXML can read text data from XML elements using just a few lines of code.
SimpleXML can convert an XML document (or XML string) into an object, for example:
- Elements are converted into a single property of the SimpleXMLElement object. When multiple elements exist at the same level, they are placed in an array.
- Attributes are accessed using an associative array, where the index corresponds to the attribute name.
- The text inside an 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 fast to use when performing basic tasks like the following:
- Read/extract data from XML files/strings
- Edit text nodes or attributes
However, when dealing with advanced XML, such as namespaces, it is better to use the Expat parser or XML DOM.
Installation
Starting from PHP 5, the SimpleXML functions are part of the PHP core. These functions can be used without installation.
PHP SimpleXML Example
Assume we have the following XML file, "note.xml":
<
note
<
to
Tove
to
<
from
Jani
from
<
heading
Reminder
heading
<
bodyDon't forget me this weekend!
body
note
Now we want to output different information from the XML file above:
Example 1
Output the keys and elements of the $xml variable (which is a SimpleXMLElement object):
Run Example »
The above code will output:
SimpleXMLElement Object ( [to] => Tove [from] => Jani [heading] => Reminder [body] => Don't forget me this weekend! )
Example 2
Output the data of each element in the XML file:
to . "" ; echo $xml -> from . "
" ; echo $xml -> heading . "
" ; echo $xml -> body ; ?>
Run Example »
The above code will output:
Tove
Jani
Reminder
Don't forget me this weekend!
Example 3
Output the element name and data of each child node:
getName ( ) . "" ; foreach ( $xml -> children ( ) as $child ) { echo $child -> getName ( ) . " : " . $child . "
" ; } ?>
Run Example »
The above code will output:
note
to: Tove
from: Jani
heading: Reminder
body: Don't forget me this weekend!
More Information about PHP SimpleXML
To learn more about the PHP SimpleXML functions, please visit our PHP SimpleXML Reference Manual.