使用这段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属性时,看起来内部指针会丢失并且不会删除这两个属性。
还有另一种方法吗?
提前致谢。
答案 0 :(得分:7)
将内部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);
}
其中任何一个都可以。