为元素创建多个属性

时间:2011-07-06 22:28:01

标签: 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-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-&gt; setAttribute('item-id','qwer')时,似乎只是写了第一个。

我是否应该创建具有不同变量名称的“$ xml_item”的多个副本(例如$ xml_item1,_item2等,但这看起来似乎过于繁琐)或者我可以以某种方式重用相同的变量($ xml_item)来创建多个条目?我的想法是根据需要使用不同的属性创建尽可能多的“item”元素。

3 个答案:

答案 0 :(得分:3)

来自createElement的php.net页面,

  

此节点不会显示在   文件,除非插入   (例如)DOMNode-&gt; appendChild()。

因此,请确保在$xml_item次来电之间继续将createElement()附加到您的DomDocument对象。
ie)$xml->appendChild($xml_item);

答案 1 :(得分:2)

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

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

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

- 要添加的每个项目的一次

您可以使用相同的变量名称 - 那样$xml-item将引用“item”元素的不同新实例,并且将无法再访问旧实例(父$xml除外)。

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

$xml->appendChild($xml_item);

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

答案 2 :(得分:0)

$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属性 然后添加属性的值并将它们附加到元素 如果有任何疑问告诉我,我将分享我的完整