如何将XML属性添加到同一个元素?

时间:2016-03-31 10:34:15

标签: php xml

我有这种类型的XML格式:

<root>
    <NotOfferNameList>
      <OfferName>...</OfferName>
      <OfferName>...</OfferName>
      <OfferName>...</OfferName>
    </NotOfferNameList>
</root>

我希望将动态属性id添加到offerName Like:

<OfferNameList>
          <OfferName id="1">...</OfferName>
          <OfferName id="2">...</OfferName>
          <OfferName id="2">...</OfferName>
        </OfferNameList>

我正在使用PHP SimpleXMLElement并使用OfferName->addAttribute('id', $i);

但是只添加第一个OfferName的id并显示如下:

 <OfferNameList>
              <OfferName id="1">...</OfferName>
              <OfferName>...</OfferName>
              <OfferName>...</OfferName>
            </OfferNameList>

任何人都可以帮我解决这个问题吗?

2 个答案:

答案 0 :(得分:0)

您可以使用 index 访问同名的第二个,第三个,等等..子元素:

//add attribute to the 2nd OfferName :
$OfferNameList->OfferName[1]->addAttribute('id', $i);

//add attribute to the 3rd OfferName :
$OfferNameList->OfferName[2]->addAttribute('id', $i);

....

答案 1 :(得分:0)

使用for()循环,您可以获得所需的结果:

$xml = simplexml_load_string( $xml );

$nodes = $xml->NotOfferNameList->OfferName;
for( $i = 0; $i < count($nodes); $i++ )
{
    $nodes[$i]->addAttribute( 'id', $i+1 );
}

echo $xml->asXML();

将输出:

<?xml version="1.0"?>
<root>
    <NotOfferNameList>
      <OfferName id="1">...</OfferName>
      <OfferName id="2">...</OfferName>
      <OfferName id="3">...</OfferName>
    </NotOfferNameList>
</root>

eval.in demo