Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

PHP XML SimpleXML

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:

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

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
<
body

Don'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.