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>

Comments are closed.

Niklas Tech Blog
Privacy Overview

This website uses cookies so that we can provide you with the best user experience possible. Cookie information is stored in your browser and performs functions such as recognising you when you return to our website and helping our team to understand which sections of the website you find most interesting and useful.