DomDocument i PHP5

In PHP, there are many different ways to create XML, but the absolut easiest way is by using DomDocument.

Start with create a new DomDocument object

$doc = new DomDocument('1.0', 'UTF-8');

Please indicate this it is to be XML version 1 and our charset are set to UTF-8

Now you need to make our root channel where all our elemeneter to be in.

$root = $doc->createElement('root');
$root = $doc->createElement('root');
$root = $doc->appendChild($root);

Now it’s time to add our first elements eg customers

foreach( $customerArray AS $key => $value )
{
	$occ = $doc->createElement('customer');
	$occ = $root->appendChild($occ);
 
	foreach( $value AS $secoundKey => $secoundValue )
	{
		$child = $doc->createElement( $secoundKey );
		$child = $occ->appendChild($child);
		$value = $doc->createCDATASection($secoundValue);
		$value = $child->appendChild($value);
	}
}

Finally, we would save our XML document and print our output to a browser.

$xml_string = $doc->saveXML();
echo $xml_string;

Leave a Reply

Your email address will not be published. Required fields are marked *

*