PHP SimpleXMLElement addChild仅显示循环中的最后一个值

问题描述:

我试图根据一些数据来生成一个XML文件,这些数据是在循环中处理的。我最后的XML输出需要看起来像这样:PHP SimpleXMLElement addChild仅显示循环中的最后一个值

<Line> 
    <Code>123</Code> 
    <Description>Acme Constructions</Description> 
    <TransactionAmount>44.00</TransactionAmount> 
    <BaseCurrency>AUD</BaseCurrency> 
</Line> 
<Line> 
    <Code>456</Code> 
    <Description>Acme Flowers</Description> 
    <TransactionAmount>23.00</TransactionAmount> 
    <BaseCurrency>AUD</BaseCurrency> 
</Line> 
<Line> 
    <Code>789</Code> 
    <Description>General Hospital</Description> 
    <TransactionAmount>19.00</TransactionAmount> 
    <BaseCurrency>AUD</BaseCurrency> 
</Line> 

我通过循环和使用addChild创建一个新的XML子记录,但我最后的XML文件只展示,不以前从循环的最后一个值那些。这里是我的PHP代码:

$xml = new SimpleXMLElement('<xml></xml>'); 

foreach ($invoiceLineItems->LineItem as $invoiceLineItem) { 

    $description = $invoiceLineItem->Description; 
    $amount = $invoiceLineItem->UnitAmount; 
    $Code = $invoiceLineItem->AccountCode; 

    $xml = $xml->addChild('Line'); 
    $xml->addChild('Code', $Code); 
    $xml->addChild('Description', $description); 
    $xml->addChild('Amount', $amount); 

} 


// Save XML 
$xml->asXML(); 

$dom = new DOMDocument('1.0'); 
$dom->preserveWhiteSpace = false; 
$dom->formatOutput = true; 
$dom->loadXML($xml->asXML()); 
$dom->save($fileName); 

这将生成的.xml文件,但它只有一个

<Line> 
... 
</Line> 

在循环中的最后一条记录,而不是一个在循环中的所有记录。

因为你从根元素$xml变量的值更新到新添加的子元素在这里:

$xml = $xml->addChild('Line'); 

使用不同的变量引用新添加的子元素:

$line = $xml->addChild('Line'); 
$line->addChild('Code', $Code); 
$line->addChild('Description', $description); 
$line->addChild('Amount', $amount); 

而且,您预期的最终XML格式不正确,因此无法使用正确的XML解析器正常生成。根目录<xml>仍然需要制作XML。