【问题标题】:How to remove attributes using PHP DOMDocument?如何使用 PHP DOMDocument 删除属性?
【发布时间】:2012-05-16 13:10:39
【问题描述】:

有了这段 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 属性时,内部指针似乎丢失了,它并没有删除这两个属性。

还有其他方法吗?

提前致谢。

【问题讨论】:

    标签: php domdocument


    【解决方案1】:

    将内部 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);
    }
    

    其中任何一个都可以。

    【讨论】:

    • 宾果游戏!我正在使用第一种方法。非常感谢你! (其他两个也很好用)
    猜你喜欢
    • 1970-01-01
    • 2022-01-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-22
    • 1970-01-01
    • 1970-01-01
    • 2014-05-31
    相关资源
    最近更新 更多