php - 为一个元素创建多个属性

标签 php xml dom

我想出了如何使用以下代码(部分)为 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/

相关文章:

javascript - 为什么开放服务器发送的事件会阻止其他 SSE、POST 或 GET?

PHP 显示数据库中的图像

java - 获取:&quot; when converting Json object to XML in Java

java - fragment 中的可点击 ListView

c# - 在 C# 中反序列化 XML 文件

php - 来自 <p> 标签的文本使用 DOM Php

JavaScript 覆盖对象方法但保持原始行为不变

php - 为什么我的数据总是正确的,并且复选框总是返回 "YES"?

javascript - 流外 DOM 操作

javascript - 具有覆盖的 Div 不会在 Chrome 中滚动