How to remove attributes using PHP DOMDocument?

若如初见. 提交于 2019-12-24 04:58:13

问题


With this piece of XML:

<my_xml>
  <entities>
    <image url="lalala.com/img.jpg" id="img1" />
    <image url="trololo.com/img.jpg" id="img2" />
  </entities>
</my_xml> 

I have to get rid of all the attributes within the image tags. So, I've done this:

<?php

$article = <<<XML
<my_xml>
  <entities>
    <image url="lalala.com/img.jpg" id="img1" />
    <image url="trololo.com/img.jpg" id="img2" />
  </entities>
</my_xml>  
XML;

$doc = new DOMDocument();
$doc->loadXML($article);
$dom_article = $doc->documentElement;
$entities = $dom_article->getElementsByTagName("entities");

foreach($entities->item(0)->childNodes as $child){ // get the image tags
  foreach($child->attributes as $att){ // get the attributes
    $child->removeAttributeNode($att); //remove the attribute
  }
}

?>

Somehow when I try to remove an from attribute within the foreach block, it looks like the internal pointer gets lost and it doesn't delete both the attributes.

Is there another way of doing that?

Thanks in advance.


回答1:


Change the inner foreach loop to:

while ($child->hasAttributes())
  $child->removeAttributeNode($child->attributes->item(0));

Or back to front deletion:

if ($child->hasAttributes()) { 
  for ($i = $child->attributes->length - 1; $i >= 0; --$i)
    $child->removeAttributeNode($child->attributes->item($i));
}

Or making a copy of the attribute list:

if ($child->hasAttributes()) {
  foreach (iterator_to_array($child->attributes) as $attr)
    $child->removeAttributeNode($attr);
}

Any of those will work.



来源:https://stackoverflow.com/questions/10619282/how-to-remove-attributes-using-php-domdocument

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!