I have tried to solve the general problem occurs in DOMNamedNodeMap that during executing for/foreachloop after executing removeAttribute('$name') for item(0), item(1) is not executing and warning occurs. Following codes give the solution of this problem that in loop item(0) should be applied rather than item($i) because after removing first attribute node now present element has only one attribute node.
<?php
$html = '<h1 id="h1test" class="h2test">Heading</h1>';
$html .= '<p align="left" class="right">Hello World</p>';
$doc = new DOMDocument();
$doc->loadHTML($html);
// remove attributes from the h1 element
$h1 = $doc->getElementsByTagName('h1')->item(0);
$length = $h1->attributes->length;
for ($i = 0; $i < $length; $i++) {
$name = $h1->attributes->item(0)->nodeName;
$value = $h1->attributes->item(0)->nodeValue;
$h1->removeAttribute($name);
echo "h1: removed attribute name :- " .$name."</br>";
echo "h1: removed attribute value :- " .$value."</br>";
}
// remove attributes from the p element
$p = $doc->getElementsByTagName('p')->item(0);
for ($i = 0; $i < $length; $i++) {
$name = $p->attributes->item(0)->nodeName;
$value = $p->attributes->item(0)->nodeValue;
$p->removeAttribute($name);
echo "p: removed attribute name :- " .$name."</br>";
echo "p: removed attribute value :- " .$value."</br>";
}
?>
OUTPUT:
h1: removed attribute name :- id
h1: removed attribute value :- h1test
h1: removed attribute name :- class
h1: removed attribute value :- h2test
p: removed attribute name :- align
p: removed attribute value :- left
p: removed attribute name :- class
p: removed attribute value :- right