[英]How to Remove unwanted Style attributes from HTML String Using 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);
}
这些都可以。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.