PHP XML Create a XML using DomDocument


To create a XML using DOMDocument,basically, we need to create all the tags and attributes using the createElement() and createAttribute() methods and them create the XML structure with the appendChild().

The example below includes tags, attributes, a CDATA section and a different namespace for the second tag:

$dom = new DOMDocument('1.0', 'utf-8');
$dom->preserveWhiteSpace = false;
$dom->formatOutput = true;

//create the main tags, without values
$books = $dom->createElement('books');
$book_1 = $dom->createElement('book');

// create some tags with values
$name_1 = $dom->createElement('name', 'PHP - An Introduction');
$price_1 = $dom->createElement('price', '$5.95');
$id_1 = $dom->createElement('id', '1');

//create  and append an attribute
$attr_1 = $dom->createAttribute('version');
$attr_1->value = '1.0';
//append the attribute

//create the second tag book with different namespace
$namespace = '';

//include the namespace prefix in the books tag
$books->setAttributeNS('', 'xmlns:ns', $namespace);
$book_2 = $dom->createElementNS($namespace,'ns:book');
$name_2 = $dom->createElementNS($namespace, 'ns:name');

//create a CDATA section (that is another DOMNode instance) and put it inside the name tag
$name_cdata = $dom->createCDATASection('PHP - Advanced');
$price_2 = $dom->createElementNS($namespace, 'ns:price', '$25.00');
$id_2 = $dom->createElementNS($namespace, 'ns:id', '2');

//create the XML structure


//saveXML() method returns the XML in a String
print_r ($dom->saveXML());

This will output the following XML:

<?xml version="1.0" encoding="utf-8"?>
<books xmlns:ns="">
    <name>PHP - An Introduction</name>
    <id version="1.0">1</id>
    <ns:name><![CDATA[PHP - Advanced]]></ns:name>