我想出了如何使用以下代码(部分)为 XML 创建 DOM 对象:
$xml_item = $xml->createElement('item');
$xml_location = $xml->createElement('location');
$xml_item->setAttribute('item-id', 'abcd');
$xml_item->appendChild($xml_location);
$xml_location->setAttribute('location-id', '1234');
$xml_location->appendChild($xml_quantity);
$xml_quantity = $xml->createElement('quantity', '0');
给予:
<item item-id="abcd">
<location location-id="1234">
<quantity>0</quantity>
</location>
</item>
我想不断添加更多不同属性的 item 元素以获得如下内容:
<item item-id="abcd">
<location location-id="1234">
<quantity>99</quantity>
</location>
</item>
<item item-id="qwer">
<location location-id="1234">
<quantity>55</quantity>
</location>
</item>
但我很难弄清楚这一点。如何使用相同的变量 $xml_item 创建具有如上所述不同属性的“item”元素的多个条目(即 abcd 和 qwer)?当我在创建“abcd”后执行另一个 $xml_item->setAttribute('item-id', 'qwer') 时,似乎只是覆盖了第一个。
我是否应该使用不同的变量名称创建“$xml_item”的多个副本(例如 $xml_item1、_item2 等,但这似乎非常乏味),或者我可以以某种方式重用相同的变量($xml_item)来创建多个条目?这个想法是根据需要创建尽可能多的具有不同属性的“item”元素。
最佳答案
来自 php.net 页面 createElement ,
This node will not show up in the document unless it is inserted with (e.g.) DOMNode->appendChild().
因此,请确保在 createElement()
调用之间不断将 $xml_item
附加到您的 DomDocument 对象。
即)$xml->appendChild($xml_item);
关于php - 为一个元素创建多个属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6603803/