简体   繁体   English

使用PHP获取和设置内联样式

[英]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? 有没有一种方法可以使用PHP在HTML片段中获取和设置DOM元素的内联样式? 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 . 我需要确定background-color是否为black ,如果是,请将其更改为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). 我尝试了phpQuery,但是它缺少.css()方法,而实现它分支似乎不起作用(至少对我而言)。

Basically, what I need is a port of jQuery's .css() method to PHP. 基本上, 我需要将jQuery的.css()方法移植到PHP。

Per Ryan P's good suggestion above, the PHP DOM functions may help you out. 根据以上Ryan P的建议, PHP DOM函数可以为您提供帮助。 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();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM