如何使用 PHP DOMDocument 删除属性


How to remove attributes using PHP DOMDocument?

使用这段XML:

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

我必须摆脱图像标签中的所有属性。所以,我已经这样做了:

<?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
  }
}
?>

不知何故,当我尝试删除 foreach 块中的 from 属性时,看起来内部指针丢失了,它不会删除这两个属性。

有没有其他方法可以做到这一点?

提前谢谢。

将内部foreach循环更改为:

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

或从后到前删除:

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

或者复制属性列表:

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

其中任何一个都将起作用。