PHP simpleXML: An overview

Written by Tom on Wednesday 22/08/07

SimpleXML is a simplified set of functions for manipulating XML data.

The basic functionality is demonstrated below. For the full documentation click here.

Example XML file.

<item name="people">
<field name="bob">
<field name="trev">

All tags in a XML file are paired tags <> and .
There is always a root tag some times called root but can be called Susy if you like.
The file is made up of parent and child nodes. item is a parent of field. field is a parent of age... etc
item and field both have an attribute called name, you can have multiple attributes separated by a space.

Open a XML file

To open a file.

function openDB($dbName){
$dbPath = "dataBase/".$dbName.".xml";
if (file_exists($dbPath)) {
$xml = simplexml_load_file($dbPath);
return $xml;
exit('Failed to open '.$dbPath);

The function above is passed the name of the XML file to open. '''simplexml_load_file''' - Interprets an XML file into an object.
That object is then passed back.

Close XML file

function saveDB($xml,$dbName){
$dbPath = "dataBase/".$dbName.".xml";

The function above is passed the name of the XML file to save/close. asXML($fileName) If the filename isn't specified, this function returns a string on success and FALSE on error. If the parameter is specified, it returns TRUE if the file was written successfully and FALSE otherwise.

Manipulate an XML file

The $xml object reflects the structure (nodes) of the XML file and can be directly manipulated thus;

echo $xml->items[0]->field[1]->age;

$xml->items[0]->field[2]->age = '10'

Note: It is not possible to iterate through the object using an index. ie

$xml->items[0]->field[$i]->age = '10'

This causes a by reference error and can be fixed by adding $t = intval($i).

$t = intval($i);
$xml->items[0]->field[$t]->age = '10'

This is limited to one index if you use the below, you get the by reference error.

$t = intval($i);
$xml->items[$t]->field[$t]->age = '10'

All is not lost the foreach construct is our friend. To iterate through the entire object is simple.

foreach($xml->item as $item){
// do something to $item
foreach($item as $field){
//do something to $field

Read/Write node attributes

echo $xml->items[0]->field[1]['name'];
$xml->items[0]->field[1]['name'] = 'bob'

Adding/Removing Node/Children

SimpeXML does not give you a method of removing a node/child.

The best you can do is set the child to NULL.