2

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?

Community
  • 1
  • 1
Farzan Najipour
  • 2,442
  • 7
  • 42
  • 81

1 Answers1

-1

Notice that you have a SimpleXMLElement $xml = null in your method signature:

private function array_to_xml(array $arr, SimpleXMLElement $xml = NULL)

Now, notice that you call this method like this:

$this->array_to_xml($test_array); // <--- No second parameter

This means that the variable $xml is null in the array_to_xml() context because you didn't give the method and 2nd parameter (so it defaults to NULL). Since you never built an actual element, it gives you

Fatal error: Call to a member function addChild() on null

You either have to give the method the necessary element

$this->array_to_xml($test_array, new SimpleXMLElement);

or build the element inside the method

private function array_to_xml(array $arr)
{
    $xml = new SimpleXMLElement();
    ...
}
Marco Aurélio Deleu
  • 4,279
  • 4
  • 35
  • 63