【问题标题】:Is it possible to extract inline CSS from HTML?是否可以从 HTML 中提取内联 CSS?
【发布时间】:2011-06-13 17:53:44
【问题描述】:

使用http://simplehtmldom.sourceforge.net/manual.htm,是否可以提取HTML文件的内联CSS?

这个解析器如果是纯html,假设(如果我错了就纠正我)它不能解析CSS标签。有没有其他方法可以在html文件中提取内联CSS?

【问题讨论】:

  • 你想解析内联css(在style元素内)还是内联样式(在元素上的style属性内)。
  • 内联 css 是 html 的一部分。它只是style 标记的内容,或者style 属性的值。因此,您应该能够使用 HTML 解析器获取这些值。
  • inline 总是指元素的内部样式属性,前者是文档内样式
  • 我可以使用解析器包含 css 解析吗?
  • 既然你已经学会了如何替换属性,你也已经知道如何获取样式属性了,所以这里是Using SimpleHtmlDom, how to remove and replace a specific attribute.的副本

标签: php html css dom


【解决方案1】:

如果你真的需要使用 simplehtmldom 来提取这个:


对于

<style>
...
</style>

使用:

$css = $html->find('style')->innertext;

对于

<div style="background:blue; color:white;"></div>

使用:

$css = $html->find('div[style]')->style;

如果有多个div 具有style 属性或多个&lt;style&gt;,您可以使用foreach 在它们之间循环。


解析样式:

在 PHP 中:

$s = 'background:blue; color:white;';

$results = [];
$styles = explode(';', $s);

foreach ($styles as $style) {
    $properties = explode(':', $style);
    if (2 === count($properties)) {
        $results[trim($properties[0])] = trim($properties[1]);
    }
}

var_dump($results);

在 JS 中

let s = 'background:blue; color:white;';

let results = {};
let styles = s.split(";");

for (let style in styles) {
    let properties = styles[style].split(":");
  if (properties.length === 2) {
    results[properties[0].trim()] = properties[1].trim();
  }
}

console.log(results);

https://jsfiddle.net/zyfhtwj2/

【讨论】:

  • 你好,请问如果我只想获取颜色属性,我该怎么做???
【解决方案2】:
find('css','div[style*="display:block;"] ')

这样你就可以找到带有display:block属性的样式。根据需要修改它,您可以获得内联 CSS。

【讨论】:

    【解决方案3】:

    使用普通的 HTML 解析器:

    1. 遍历所有元素
    2. 如果元素的标签是style,则获取元素的内容
    3. 如果元素具有属性style,则获取该属性的值。

    【讨论】:

      【解决方案4】:

      这应该可行:

      $doc = new DOMDocument();
      $doc->loadHTML('<html><body style="color: red"></body></html>');
      
      $els = $doc->getElementsByTagName('*');
      
      for($i = 0; $i < $els->length; $i++)
        echo $els->item($i)->getAttribute('style'); // color: red
      

      【讨论】:

        猜你喜欢
        • 2011-05-04
        • 2011-03-13
        • 1970-01-01
        • 1970-01-01
        • 2019-05-27
        • 2012-03-29
        • 2016-05-31
        • 1970-01-01
        • 2023-03-22
        相关资源
        最近更新 更多