Stas Bichenko
Stas Bichenko

Reputation: 13263

Get and set inline styles with PHP

Is there a way to get and set inline styles of DOM elements inside an HTML fragment with PHP? Example:

<div style="background-color:black"></div>

I need to get whether the background-color is black and if it is, change it to white. (This is an example and not the actual goal)

I tried phpQuery, but it lacks the .css() method, while the branch that implements it doesn't seem to work (at least for me).

Basically, what I need is a port of jQuery's .css() method to PHP.

Upvotes: 2

Views: 2230

Answers (1)

jamesplease
jamesplease

Reputation: 12869

Per Ryan P's good suggestion above, the PHP DOM functions may help you out. Something like this might do what you want with that particular example.

$my_url = 'index.php';
$dom = new DOMDocument; 
$dom->loadHTMLfile($my_url);

$divs = $dom->getElementsByTagName('div');
foreach ($divs as $div) {
    $div_style = $div->getAttribute('style');
    if ($div_style && $div_style=='background-color:black;') {
    $div->setAttribute('style','background-color:white;');
    }
}

echo $dom->saveHTML();

Upvotes: 2

Related Questions