Thursday, 21 August 2008

Creating XML with SimpleXML and PHP

Following on from my Introduction to SimpleXML with PHP, SimpleXML can also be used to create XML documents.

The XML example in the previous post:

<?xml version="1.0"?>
<message>
<subject>Hello</subject>
<from>user@example.com</from>
<to>user2@example.com</to>
<body>Hello World</body>
</message>
Can be created with the following code:

<?php
//create SimpleXML object
$xml = simplexml_load_string("<message></message>");

//add subject element
$xml->addChild('subject','Hello');

//add from element
$xml->addChild('from','user@example.com');

//add to element
$xml->addChild('to','user2@example.com');

//add body element
$xml->addChild('body','Hello World');

//output XML
echo $xml->asXML();
?>

You can also add sub elements to elements that you create: for example if your XML files was to have a list of messages:

<?php
$xml = simplexml_load_string("<messages></messages>");

//add child to xml object and return new object for that child
$message1 = $xml->addChild('message');
$message1->addChild('subject','Hello');
$message1->addChild('from','user@example.com');
$message1->addChild('to','user2@example.com');
$message1->addChild('body','Hello World');

//add second child to xml object and return new object for that child
$message2 = $xml->addChild('message');
$message2->addChild('subject','Hello Again');
$message2->addChild('from','user@example.com');
$message2->addChild('to','user2@example.com');
$message2->addChild('body','Hello World Take 2');

//output XML
echo $xml->asXML();
?>
This will output:
<?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>

No comments: