<?php
$data = array(
'id' => 1,
'name' => 'Jacopo',
'male' => true,
'birthday' => new DateTime('1988-07-26'),
'hobbies' => array(
'Programming',
'TV Shows',
'Skiing'
)
);
$rootXMLElement = '<data />';
$xml = new SimpleXMLElementExtended('<?xml version="1.0"?>' . $rootXMLElement);
arrayToXML($data, $xml);
echo $xml->asXML();
// http://coffeerings.posterous.com/php-simplexml-and-cdata
class SimpleXMLElementExtended extends SimpleXMLElement
{
public function addCDATA($text)
{
$node = dom_import_simplexml($this);
$no = $node->ownerDocument;
$node->appendChild($no->createCDATASection($text));
}
public function getParentNode()
{
return current($this->xpath('parent::*'));
}
}
function arrayToXML($data, &$xml)
{
foreach ($data as $key => $value) {
if (is_numeric($key)) {
$key = 'item';
}
if (is_array($value)) {
if (!is_numeric($key)) {
$node = $xml->addChild($key);
arrayToXML($value, $node);
} else {
// $currentNodeName = $xml->getName();
// $currentNodeNameSingular = @Inflector::singularize($currentNodeName);
// if ( $currentNodeName != 'data'
// && $currentNodeName != $currentNodeNameSingular
// ) {
// $key = $currentNodeNameSingular;
// } else {
// $key = 'item';
// }
$node = $xml->addChild($key);
arrayToXML($value, $node);
}
} else {
if (strpos($value, '<') === false) {
$xml->addChild($key, $value);
} else {
$xml->addChild($key)->addCDATA($value);
}
}
}
}
preferences:
41.15 ms | 402 KiB | 5 Q