PHP-5 DomDocument: Creating a Basic XML

DomDocument is a powerful library of PHP-5 to create XML. In this article, I will try to explain the basics of DomDocument and then will create a couple of simple XML files.

First, lets have a look at a simple XML file:
Taken from W3C’s example:

<?xml version="1.0" encoding="ISO-8859-1"?>
>note>
	<to>Tove>/to>
	<from>Jani>/from>
	<heading>Reminder>/heading>
	<desc>Don't forget me this weekend!</desc>
</note>

We see an XML version and character encoding at the first line, followed by XML Tags/Elements. I am going to create the above XML using DomDocument

In PHP, at first let’s create an instance of DomDocument and initialize it, and set its version and character encoding

// 1st param takes version and 2nd param takes encoding;
$dom = new DomDocument("1.0", "ISO-8859-1");

// it can also be set later, like below, if you decide not to declare at first line:
$dom->version  = "1.0";
$dom->encoding = "ISO-8859-1";

To create a Node, the following method is used:

$dom->createElement('NODE_NAME');
// OR
$dom->createElement('NODE_NAME', 'NODE_VALUE');

To set a node as a child node of another node:

$dom->appendChild( 'PREVIOUSLY_CREATED_NODE' );

Now, we are going to create Nodes:

// we create a XML Node and store it in a variable called noteElem;
$noteElem  = $dom->createElement('note'); 

// createElement takes 2 param also, with 1st param takes the node Name, and 2nd param is node Value
$toElem    = $dom->createElement('to', 'Tove');

// now, we add $toElem as a child of $noteElem
$noteElem->appendChild( $toElem );

//we don't need to create a new variable for each node, we can do the following to quicken the steps:
$noteElem->appendChild ( $dom->createElement('from', 'Jani') );
$noteElem->appendChild ( $dom->createElement('heading', 'Reminder') );
$noteElem->appendChild ( $dom->createElement('desc', 'Dont forget me this weekend!') );

So, $noteElem, now has all its child added properly. So we add $noteElem to $dom and then we can save it as File or output as XML like below:

// add $noteElem to the main dom
$dom->appendChild( $noteElem );

// $dom has entire XML, but, it's not clearly formatted, i.e there's no space or new lines in between tags, so I do this:
$dom->formatOutput = true; // this adds spaces, new lines and makes the XML more readable format. 

// now $dom has all the entire XML properly, we can output it like below, 
$xmlString = $dom->saveXML(); // $xmlString contains the entire String

// or we can save it as XML
$dom->save('filename.xml'); // returns true/false upon failure or success 

The above was a very simple XML, with no Attributes or CDATA/PCDATA on any element, so, lets say we have the following XML below:

<?xml version="1.0" encoding="ISO-8859-1"?>
<library>
 <book isbn="781">
   <name>SCJP 1.5</name>
   <info><![CDATA[Sun Certified Java Programmer book]]></info>
  </book>
</library>

To set Attribute of any Element, use:

$dom->setAttribute('name', 'value');

To create a CDATA, use:

$dom->createCDATASection('The CData for the Node');

Below, I will create the above XML

$dom 	  = new DomDocument("1.0", "ISO-8859-1");
$library  = $dom->createElement('library');

//1st item
$bookElem = $dom->createElement('book');
// set it's attribute
$bookElem->setAttribute('isbn', '781');
$bookElem->appendChild( $dom->createElement('name', 'SCJP 1.5') );

//create infoElement and append a CDATA as its child
$infoElem = $dom->createElement('info');
$infoElem->appendChid( $dom->createCDATASection('Sun Certified Java Programmer book') );

$bookElem->appendChild( $infoElem );
$library->appendChild( $bookElem );
$dom->appendChild( $library );

$xmlData  = $dom->saveXML();

Sometimes you may want to have comments in an XML, use:

$dom->createComment('some comment data');

I think thats about it. One important thing to know that DomDocument can be used to create HTML files. It have several functions like saveHTML, please read the PHP 5’s official Documentation to know more.

  • AdrianP

    Thanks! Useful indeed.

  • Binod Gope

    I am getting unexpected in my xml file how to remove that tag
    here is my code:

    $data=$this->property_model->getreservations_data($start_date,$end_date);

    $xml= new DOMDocument(“1.0″,”UTF-8”);
    $xml->FormatOutput=true;
    $Reservations=$xml->createElement(‘Reservations’);
    $Reservations=$xml->appendChild($Reservations);

    foreach ($data as $key) {
    $Reservation=$xml->createElement(‘Reservation’);
    $Reservation->setAttribute(‘property_id’,$key[‘prop_id’]);
    $Reservation->setAttribute(‘reservation_id’,$key[‘booking_id’]);
    $Reservation=$Reservations->appendChild($Reservation);

    $EmailAddress=$xml->createElement(‘EmailAddress’,$key[’email’]);
    $EmailAddress=$Reservation->appendChild($EmailAddress);
    $fromdate=date(‘Y-m-d’,strtotime($key[‘travel_from_date’]));
    $ArrivalDate=$xml->createElement(‘ArrivalDate’,$fromdate);
    $ArrivalDate=$Reservation->appendChild($ArrivalDate);
    $todate=date(‘Y-m-d’,strtotime($key[‘travel_to_date’]));
    $DepartureDate=$xml->createElement(‘DepartureDate’,$todate);
    $DepartureDate=$Reservation->appendChild($DepartureDate);

    if ($key[‘order_status’]==’Success’) {
    $Status=$xml->createElement(‘Status’);
    $Status->setAttribute(‘value’,’reserved’);
    $Status=$Reservation->appendChild($Status);
    }else{

    $Status=$xml->createElement(‘Status’);
    $Status->setAttribute(‘value’,’cancelled’);
    $Status=$Reservation->appendChild($Status);
    }
    }
    echo $xml->saveXML();

    }

    output in production:

    kunal31393@gmail.com2015-12-072018-05-06
    output in localhost:

    yogeshb@gmail.com2016-10-202017-05-17</Departur