Search code examples
phpdomattributesanchorhref

removeAttributeNode which executed only one time in loop in php5 dom


I am searching for script which remove all attributes except href in anchor tag. I found some scripts which all very similar following solution i write.

$okattrs = array(
            'a' => array('href' => true),
            );

$content = '<div id="att"><a class="pl" title="hit me" id="myid" href="http://google.com" >Click On Google</a></div>';
$doc = new DomDocument();
$doc->loadHTML($content);

$a_tags = $doc->getElementsByTagName('a');
foreach($a_tags as $k => $a_tag_obj) {
    foreach ($a_tag_obj->attributes as $name => $attrNode)
    {
        if (!isset($okattrs[$a_tag_obj->nodeName][$name]))
        {
            $a_tag_obj->removeAttributeNode($attrNode);
        }
    }
}
echo    $content1=$doc->saveHTML();

Now my problem is that it remove only first attribute which is 'class'. I debug and found if i remove line having removeAttributeNode loop works fine 4 times, But in case of using this loop just work one time, remove only first attribute and breaks.

Anybody have this problem before or have a solution?


Solution

  • Finally i make the code running. just one change that move removeAttributeNode to another loop.

    foreach($a_tags as $a_tag_obj) { 
        $attribute_list = array(); 
        foreach ($a_tag_obj->attributes as $name => $attrNode) { 
            if (!isset($okattrs[$a_tag_obj->nodeName][$name])) { 
                $attribute_list[] = $name; 
            }    
        } 
        for($i=0;$i<sizeof($attribute_list);$i++) { 
            $a_tag_obj->removeAttribute($attribute_list[$i]); 
        }
    }