如何使用PHP DOMDocument删除属性? [英] How to remove attributes using PHP DOMDocument?

查看:116
本文介绍了如何使用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> 

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

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

?>

当我尝试在foreach块中删除from属性时,内部指针看起来像丢失并且不会删除这两个属性。

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.

还有另一种方法吗?

谢谢

推荐答案

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

其中任何一个都可以使用。

Any of those will work.

这篇关于如何使用PHP DOMDocument删除属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆