问题
With this piece of 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
}
}
?>
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.
Is there another way of doing that?
Thanks in advance.
回答1:
Change the inner foreach
loop to:
while ($child->hasAttributes())
$child->removeAttributeNode($child->attributes->item(0));
Or back to front deletion:
if ($child->hasAttributes()) {
for ($i = $child->attributes->length - 1; $i >= 0; --$i)
$child->removeAttributeNode($child->attributes->item($i));
}
Or making a copy of the attribute list:
if ($child->hasAttributes()) {
foreach (iterator_to_array($child->attributes) as $attr)
$child->removeAttributeNode($attr);
}
Any of those will work.
来源:https://stackoverflow.com/questions/10619282/how-to-remove-attributes-using-php-domdocument