<?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:
<?phpThe $xml->message object is seen as an array so outputs the following:
$xml = simplexml_load_file("test.xml");
foreach ($xml->message as $message)
{
print_r($message);
}
?>
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:
Would output:
<?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);
}
?>
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
)
0 comments:
Post a Comment