Create XML document with PHP SimpleXML

In my work I often need to create new XML documents and with the introduction of SimpleXML in PHP 5.0.1 this has become very easy. Before PHP 5 I used the DOM-XML class which can be a little cumbersome for small and simple XML documents. I’m here going to create a simple XML document as an example of how I now normally do it.

$xml = new SimpleXMLElement('<?xml version="1.0" encoding="utf-8"?><mydoc></mydoc>');

$xml->addAttribute('version', '1.0');
$xml->addChild('datetime', date('Y-m-d H:i:s'));

$person = $xml->addChild('person');
$person->addChild('firstname', 'Someone');
$person->addChild('secondname', 'Something');
$person->addChild('telephone', '123456789');
$person->addChild('email', 'me@something.com');

$address = $person->addchild('address');
$address->addchild('homeaddress', 'Andersgatan 2, 432 10 Göteborg');
$address->addChild('workaddress', 'Andersgatan 3, 432 10 Göteborg');

echo $xml->asXML();

This will create a XML document looking like this:

<?xml version="1.0" encoding="utf-8"?>
<mydoc version="1.0">
  <datetime>2010-12-12 16:45:12</datetime>
  <person>
    <firstname>Anders</firstname>
    <lastname>Andersson</lastname>
    <telephone>123456789</telephone>
    <email>me@something.com</email>
    <address>
      <homeaddress>Andersgatan 2, 432 10 Göteborg</homeaddress>
      <workaddress>Andersgatan 3, 432 10 Göteborg</workaddress>
    </address>
  </person>
</mydoc>
  1. nice tuts 🙂

  2. Works great. Thanks for the script 🙂

  3. Thanks, but the DOMDocument class looks better.

Leave a Comment


NOTE - You can use these HTML tags and attributes:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>