Skip to content

Instantly share code, notes, and snippets.

@martinbean
Created November 16, 2012 21:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save martinbean/4090910 to your computer and use it in GitHub Desktop.
Save martinbean/4090910 to your computer and use it in GitHub Desktop.
Building an XML file with DOMDocument
<?php
$products = array(
array(
'title' => 'Product #1',
'description' => 'Lorem ipsum'
),
array(
'title' => 'Product #2',
'description' => 'Lorem ipsum'
)
);
$xmlDocument = new DOMDocument('1.0', 'utf-8');
$xmlDocument->formatOutput = true;
$productsNode = $xmlDocument->createElement('products');
$xmlDocument->appendChild($productsNode);
foreach ($products as $product) {
$productNode = $xmlDocument->createElement('product');
$titleNode = $xmlDocument->createElement('title');
$titleNode->appendChild($xmlDocument->createTextNode($product['title']));
$descriptionNode = $xmlDocument->createElement('description');
$descriptionNode->appendChild($xmlDocument->createCDATASection($product['description']));
$productNode->appendChild($titleNode);
$productNode->appendChild($descriptionNode);
$productsNode->appendChild($productNode);
}
echo $xmlDocument->saveXML();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment