我正在尝试让 PHP 将嵌套数组转换为 XML 文档。我一直无法解决为什么没有子元素的数组完全从 XML 输出中隐藏;我希望他们在 XML 中也显示为没有孩子。
这是相关的代码片段:
private function response_xml_encode($node, $data)
{
if ($node == null) return false;
if (!is_array($data)) return false;
foreach ($data as $key => $value)
{
if (is_array($value) && !$this->response_xml_encode_assocarray($value))
{
foreach ($value as $val)
$node->addChild($key, htmlentities($val));
}
else if (is_array($value))
{
$this->response_xml_encode($node->addChild($key), $value);
}
else if (!$this->response_xml_encode_validkey($key))
{
$subnode = $node->addChild($node->getName(), htmlentities($value));
$subnode->addAttribute('keyinvalid', 'true');
$subnode->addAttribute('key', htmlentities($key));
}
else
{
$node->addChild($key, htmlentities($value));
}
}
}
private function response_xml_encode_assocarray($arr)
{
// Let's us know if this array has associative key value pairs, or if it has numeric key value pairs
// Returns TRUE if this array has any non-numeric key in it
foreach ($arr as $key => $value)
{
if (!is_numeric($key)) return true;
}
return false;
}
private function response_xml_encode_validkey($key)
{
if (strpos('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz_', substr($key, 0, 1)) === false) return false;
return (preg_match('/[^A-Za-z_-]/s', $key) === 0);
}
然后我使用以下方法调用它:
$response = array(
'result' => 0,
'message' => 'Success.',
'function' => 'test',
'data' => array(
'GET' => $_GET,
'POST' => $_POST,
'foo' => array(
'bar' => array(
'bad' => array(
'wolf' => array(
'some_value' => 'testtesttest'
)
)
)
)
)
);
$root = new SimpleXMLElement('<?xml version="1.0" encoding="UTF-8"?><response/>');
$this->response_xml_encode($root, $response);
return $root->asXML();
请注意,$_GET
and$_POST
是空数组。
以下是返回的内容:
<?xml version="1.0" encoding="UTF-8"?>
<response>
<result>0</result>
<message>Success.</message>
<function>test</function>
<data>
<foo>
<bar>
<bad>
<wolf>
<some_value>testtesttest</some_value>
</wolf>
</bad>
</bar>
</foo>
</data>
</response>
但预期的是它会在它显示<GET/>
之前<POST/>
显示<foo>
:
<?xml version="1.0" encoding="UTF-8"?>
<response>
<result>0</result>
<message>Success.</message>
<function>test</function>
<data>
<GET/>
<POST/>
<foo>
<bar>
<bad>
<wolf>
<some_value>testtesttest</some_value>
</wolf>
</bad>
</bar>
</foo>
</data>
</response>