APIを構築しています。関数の1つは、動的な数のレコードを持つ多次元配列を返します。単一のレコードが返されると、array2xml関数は正常に機能しますが、複数ある場合は、「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>