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

时间:2017-04-18 06:36:22

标签: php xml foreach simplexml

我试图根据我在循环中处理的一些数据生成XML文件。我的最终XML输出需要如下所示:

<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> 

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

1 个答案:

答案 0 :(得分:0)

因为您在此处将$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。