romulodl
romulodl

Reputation: 101

How to remove attributes using PHP DOMDocument?

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.

Upvotes: 3

Views: 11608

Answers (1)

Matthew
Matthew

Reputation: 48284

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.

Upvotes: 10

Related Questions