Created
November 16, 2012 21:07
-
-
Save martinbean/4090910 to your computer and use it in GitHub Desktop.
Building an XML file with DOMDocument
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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