KARTHI SRV KARTHI SRV - 2 months ago 13
PHP Question

Convert multiple arrays into XML in CakePHP

This is my array:

Array (
[Payments] => Array (
[0] => Array (
[Payment] => Array (
[Invoice] => Array (
[InvoiceNumber] => INV-0084
)
[Account] => Array (
[Code] => 260
)
[Date] => 1969-12-31T17:00:00
[Amount] => 119
)
)
[1] => Array (
[Payment] => Array (
[Invoice] => Array (
[InvoiceNumber] => INV-0085
)
[Account] => Array (
[Code] => 260
)
[Date] => 1969-12-31T17:00:00
[Amount] => 132
)
)
)
)


I need to convert it to XML data. I have used the CakePHP library to convert the XML data.

<Payments>
<Payment>
<Invoice>
<InvoiceNumber>INV-0084</InvoiceNumber>
</Invoice>
<Account>
<Code>260</Code>
</Account>
<Date>2016-06-01T17:00:00 </Date>
<Amount>119</Amount>
</Payment>
<Payment>
<Invoice>
<InvoiceNumber>INV-0085</InvoiceNumber>
</Invoice>
<Account>
<Code>260</Code>
</Account>
<Date>2016-06-01T17:00:00 </Date>
<Amount>132</Amount>
</Payment>




I had used the function

$paymentXml = Xml::fromArray($paymentXmlData, array('format' =>'tags'));
$paymentXml = $paymentXml->asXML();


The error I got was:


SimpleXMLElement::__construct(): Entity: line 3: parser error : Extra content at the end of the document","file":"/var/www/html/limeactuarial/lib/Cake/Utility/Xml.php","line":197


How do I solve these by using the default library?

ndm ndm
Answer

Check the documentation. Your data is not correctly structured; nodes need to be nested under a single key, which serves as the name for the nodes.

What you are doing there will effectively create multiple root nodes, like:

<Payments>
    <Payment>
        <Invoice>
            <InvoiceNumber>INV-0084</InvoiceNumber>
        </Invoice>
        ...
    </Payment>
</Payments>
<Payments>
    <Payment>
        <Invoice>
            <InvoiceNumber>INV-0085</InvoiceNumber>
        </Invoice>
        ...
    </Payment>
</Payments>

Which is invalid XML. Your data needs to be structured like this, where Payments will be the root node, containing two Payment nodes.

array(
    'Payments' => array(
        'Payment' => array(
            array(
                'Invoice' => array(
                    'InvoiceNumber' => 'INV-0084'
                ),
                'Account' => array(
                    'Code' => '260'
                ),
                'Date' => '1969-12-31T17:00:00',
                'Amount' => '119'
            ),
            array(
                'Invoice' => array(
                    'InvoiceNumber' => 'INV-0085'
                ),
                'Account' => array(
                    'Code' => '260'
                ),
                'Date' => '1969-12-31T17:00:00',
                'Amount' => '132'
            )
        )
    )
)

See also: