为一个元素创建多个属性


Creating multiple attributes for an element

我用以下代码(部分代码(了解了如何为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-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_item1、_item2等(创建"$xml_item"的多个副本吗?或者我可以以某种方式重用同一个变量($xml_iitem(来创建多个条目吗?这个想法是创建尽可能多的具有不同属性的"item"元素。

从createElement的php.net页面,

此节点不会显示在文档,除非插入(例如(DOMNode->appendChild((。

因此,只需确保在createElement()调用之间将$xml_item附加到DomDocument对象即可
ie($xml->appendChild($xml_item);

我认为您缺少的是$xml-item是对对象的引用-您对其函数之一的每次调用都是在对象的同一实例上调用的,因此setAttribute将覆盖您之前设置的任何值。

要创建对象的新实例,您需要调用

$xml_item = $xml->createElement('item');

再次-对于要添加的每个项目一次。

您可以使用相同的变量名-这样$xml-item将引用"item"元素的另一个新实例,并且旧实例将不再可访问(从父$xml访问除外(。

正如brian_d所提到的,每次致电createElement后,您都需要致电

$xml->appendChild($xml_item);

因此所有项目都将出现在父DOM文档中。

$img = $doc->createElement( "img" );
  $imgattr = $doc->createAttribute( "src" );
  $imgattr1 = $doc->createAttribute( "width" );
  $imgattr1->value = 300;
  $imgattr->value = $image['path'];// this the source of my image
  $img->appendChild( $imgattr );
  $img->appendChild( $imgattr1 );
  $b->appendChild( $img );

这里img是元素,我添加了src和width属性然后添加属性的值并将其附加到元素如果有任何问题告诉我,我将分享我的完整