我正在构建一个API。其中一个函数返回一个具有动态记录数的多维数组。当返回单个记录时,我的array2xml函数工作正常,但是当存在多于1时,我得到错误“XML解析错误:文档元素之后的垃圾”。我已经包含了应该将其转换为xml的函数以及下面未转换格式的数组:
/* Setting XML header */
@header ("content-type: text/xml charset=utf-8");
/* Initializing the XML Object */
$xml = new XmlWriter();
$xml->openMemory();
$xml->startDocument('1.0', 'UTF-8');
$xml->startElement('callback');
$xml->writeAttribute('xmlns:xsi','http://www.w3.org/2001/XMLSchema-instance');
$xml->writeAttribute('xsi:noNamespaceSchemaLocation','schema.xsd');
/* Function that converts each array element to an XML node */
function write(XMLWriter $xml, $data){
foreach($data as $key => $value){
if(is_array($value)){
$xml->startElement($key);
write($xml, $value);
$xml->endElement();
continue;
}
$xml->writeElement($key, $value);
}
}
/* Calls previously declared function, passing our results array as parameter */
write($xml, $data);
/* Closing last XML node */
$xml->endElement();
/* Printing the XML */
echo $xml->outputMemory(true);
正在转换的数组:
Array
(
[0] => Array
(
[Scope_CH] => Intruder Alarm Systems (ACPO) Certified
[Scope_ID] => 1
)
[1] => Array
(
[Scope_CH] => CCTV Systems Approved
[Scope_ID] => 5
)
)
如果我从xml创建者中删除标题,则输出为:
<?xml version="1.0" encoding="UTF-8"?>
<callback xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="schema.xsd"><Scope_CH>Intruder Alarm Systems (ACPO) Certified </Scope_CH><Scope_ID>1</Scope_ID></callback><Scope_CH>CCTV Systems Approved </Scope_CH><Scope_ID>5</Scope_ID>