Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add an attribute to an HTML element

Tags:

html

php

I can't quite figure it out, I'm looking for some code that will add an attribute to an HTML element.

For example lets say I have a string with an <a> in it, and that <a> needs an attribute added to it, so <a> gets added style="xxxx:yyyy;". How would you go about doing this?

Ideally it would add any attribute to any tag.

like image 215
MintDeparture Avatar asked Oct 20 '10 23:10

MintDeparture


1 Answers

It's been said a million times. Don't use regex's for HTML parsing.

    $dom = new DOMDocument();
    @$dom->loadHTML($html);
    $x = new DOMXPath($dom);

    foreach($x->query("//a") as $node)
    {   
        $node->setAttribute("style","xxxx");
    }
    $newHtml = $dom->saveHtml()
like image 183
Byron Whitlock Avatar answered Oct 08 '22 13:10

Byron Whitlock