【发布时间】: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->asXML();之前添加echo <pre>;以查看您的xml -
@splash58 解析错误:语法错误,意外'
-
回声 "
"; - eval.in/603925
-
@splash58 它没有记录任何东西eval.in/603937
-
你没有看到你想要的xml吗?