0

我正在构建一个 API。其中一个函数返回具有动态记录数的多维数组。当返回单个记录时,我的 array2xml 函数工作正常,但是当有多个记录时,我收到错误“XML Parsing Error: junk after document element”。我在下面包含了应该将其转换为 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>
4

0 回答 0