I read this link and another examples. I want to convert array to XML using Laravel (and php7) . Here is my code :
public function siteMap()
{
if (function_exists('simplexml_load_file')) {
echo "simpleXML functions are available.<br />\n";
} else {
echo "simpleXML functions are not available.<br />\n";
}
$array = array (
'bla' => 'blub',
'foo' => 'bar',
'another_array' => array (
'stack' => 'overflow',
),
);
$xml = simplexml_load_string('<root/>');
array_walk_recursive($array, array ($xml, 'addChild'));
print $xml->asXML();
}
It's my first try . it returns me :
simpleXML functions are available.
blafoostack
My second try is :
public function siteMap()
{
$test_array = array (
'bla' => 'blub',
'foo' => 'bar',
'another_array' => array (
'stack' => 'overflow',
),
);
$this->array_to_xml($test_array);
}
private function array_to_xml(array $arr, SimpleXMLElement $xml = NULL)
{
foreach ($arr as $k => $v) {
is_array($v)
? array_to_xml($v, $xml->addChild($k))
: $xml->addChild($k, $v);
}
return $xml;
}
I had an error in this situation :
Fatal error: Call to a member function addChild() on null
Here what I want :
<?xml version="1.0"?>
<root>
<blub>bla</blub>
<bar>foo</bar>
<overflow>stack</overflow>
</root>
Any suggestion?