【问题标题】:Laravel - SimpleXMLElement' not foundLaravel - 未找到 SimpleXMLElement'
【发布时间】:2016-11-14 14:35:27
【问题描述】:

我阅读了this link 和其他示例。我想使用 Laravel (和 php7) 将数组转换为 XML。 这是我的代码:

   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();
    }

这是我的第一次尝试。它返回我:

simpleXML functions are available.
blafoostack

我的第二次尝试是:

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;
}

在这种情况下我遇到了错误:

致命错误:在 null 上调用成员函数 addChild()

这是我想要的:

<?xml version="1.0"?>
<root>
  <blub>bla</blub>
  <bar>foo</bar>
  <overflow>stack</overflow>
</root>

有什么建议吗?

【问题讨论】:

  • 在第一个代码中的print $xml-&gt;asXML(); 之前添加echo &lt;pre&gt;; 以查看您的xml
  • @splash58 解析错误:语法错误,意外'
  • 回声 "
    "; - eval.in/603925
  • @splash58 它没有记录任何东西eval.in/603937
  • 你没有看到你想要的xml吗?

标签: php arrays laravel php-7


【解决方案1】:

请注意,您的方法签名中有 SimpleXMLElement $xml = null

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

现在,注意你是这样调用这个方法的:

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

这意味着array_to_xml() 上下文中的变量$xmlnull,因为您没有提供方法和第二个参数(因此它默认为NULL)。由于您从未构建过实际元素,因此它为您提供了

致命错误:在 null 上调用成员函数 addChild()

你要么必须为方法提供必要的元素

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

或在方法内构建元素

private function array_to_xml(array $arr)
{
    $xml = new SimpleXMLElement();
    ...
}

【讨论】:

    猜你喜欢
    • 2018-03-18
    • 2020-11-10
    • 2018-05-03
    • 2020-08-22
    • 2021-03-21
    • 2017-07-17
    • 2019-10-20
    • 2019-08-10
    • 2021-02-27
    相关资源
    最近更新 更多