Friday, 22 August 2008

Parsing XML using SimpleXML and PHP

One of the very useful things about the SimpleXML extension in PHP is parsing XML data very simply and easily, for example, using the XML file created in a previous post which looks as follows:
<?xml version="1.0"?>
<messages>
<message>
<subject>Hello</subject>
<from>user@example.com</from>
<to>user2@example.com</to>
<body>Hello World</body>
</message>
<message>
<subject>Hello Again</subject>
<from>user@example.com</from>
<to>user2@example.com</to>
<body>Hello World Take 2</body>
</message>
</messages>

Assuming the xml is located in a file called test.xml we can loop through the contents with the following code:
<?php
$xml = simplexml_load_file("test.xml");

foreach ($xml->message as $message)
{
print_r($message);
}
?>
The $xml->message object is seen as an array so outputs the following:

SimpleXMLElement Object
(
[subject] => Hello
[from] => user@example.com
[to] => user2@example.com
[body] => Hello World
)
SimpleXMLElement Object
(
[subject] => Hello Again
[from] => user@example.com
[to] => user2@example.com
[body] => Hello World Take 2
)

It is also very easy to manipulate data within the array, for example to change to to address on the second message:

<?php
$xml = simplexml_load_file("test.xml");

//find the second element, (starting from 0)
$xml->message[1]->to = "user3@example.com";

foreach ($xml->message as $message)
{
print_r($message);
}
?>
Would output:

SimpleXMLElement Object
(
[subject] => Hello
[from] => user@example.com
[to] => user2@example.com
[body] => Hello World
)
SimpleXMLElement Object
(
[subject] => Hello Again
[from] => user@example.com
[to] => user3@example.com
[body] => Hello World Take 2
)

1 comment:

John Barness said...

I think when it comes to data backup, especially if it is related to business documentation or so, there should be really best virtual data room providers involved. Data loss may have a very high price in the business world.