如何在PHP中使用Dom Document查找Dom元素的样式属性?

Sha*_*jan 3 html php dom domdocument

我使用 PHP Dom Document 从文件中读取 HTML Dom 元素。

  $html = file_get_contents(public_path() . 'content.html');
    $dom = new \DOMDocument();
    $dom->loadHTML($html);
    var_dump($dom->getElementById('panel_header'));
Run Code Online (Sandbox Code Playgroud)

我可以通过元素的ID来定位元素,并读取元素的内容等等。

但我找不到它的样式属性。

因为我需要克隆它或使用新参数进行更改。

如何读取其样式属性并改变?

是否可以 ?

还有其他解决方案吗?

Suc*_*mar 5

你可以尝试这个:如果 CSS 位于同一页面上,你可以尝试这个:

    $html = file_get_contents('testing.html');
    $dom = new DOMDocument();
    $dom->loadHTML($html);
    $div = $dom->getElementById('test');
    if ($div->hasAttributes()) {
        foreach ($div->attributes as $attr) {
            $name = $attr->nodeName;
            $value = $attr->nodeValue;
            if( strcmp($name,"class") == 0){
                $x=getStyle($dom->textContent,".$value{","}");
                echo "<pre>";
                print_r($x);
             }
             if( strcmp($name,"id") == 0){
                $idCss=getStyle($dom->textContent,"#$value{","}");
                echo "<pre>";
                print_r($idCss);
             }
         }
    }


     function getStyle($string, $start, $end){
        $string = ' ' . $string;
        $ini = strpos($string, $start);
        if ($ini == 0) return '';
        $len = strpos($string, $end, $ini);
        return substr($string, $ini, $len);
    }
Run Code Online (Sandbox Code Playgroud)

更新您可以使用的样式。

$div->setAttribute('style', 'background-color:blue;'); 
     echo $dom->saveHTML(); exit;. 
Run Code Online (Sandbox Code Playgroud)

测试.html:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<div id="test" class="stl" style="width:100px;">

</div>
</body>
</html>

<style>
.stl{
background-color:green;
}

</style>
Run Code Online (Sandbox Code Playgroud)

输出:

.stl{
background-color:green;
}
Run Code Online (Sandbox Code Playgroud)

如果您只寻找风格,您可以这样做:

$html = file_get_contents('testing.html');
        $dom = new DOMDocument();
        $dom->loadHTML($html);
    $div = $dom->getElementById('test');
    if ($div->hasAttributes()) {
        echo $div->getAttribute('style');//width:100px;
    }
Run Code Online (Sandbox Code Playgroud)