php - Laravel - SimpleXMLElement' not found -
i read this link , examples. want convert array xml using laravel (and php7) . here code :
public function sitemap() { if (function_exists('simplexml_load_file')) { echo "simplexml functions available.<br />\n"; } else { echo "simplexml functions 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 first try . returns me :
simplexml functions available. blafoostack my second try :
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 $k => $v) { is_array($v) ? array_to_xml($v, $xml->addchild($k)) : $xml->addchild($k, $v); } return $xml; } i had error in situation :
fatal error: call member function addchild() on null
here want :
<?xml version="1.0"?> <root> <blub>bla</blub> <bar>foo</bar> <overflow>stack</overflow> </root> any suggestion?
notice have simplexmlelement $xml = null in method signature:
private function array_to_xml(array $arr, simplexmlelement $xml = null) now, notice call method this:
$this->array_to_xml($test_array); // <--- no second parameter this means variable $xml null in array_to_xml() context because didn't give method , 2nd parameter (so defaults null). since never built actual element, gives
fatal error: call member function addchild() on null
you either have give method necessary element
$this->array_to_xml($test_array, new simplexmlelement); or build element inside method
private function array_to_xml(array $arr) { $xml = new simplexmlelement(); ... }
Comments
Post a Comment