Php Html Dom 解析器没有获取 <style> 和 <script> 元素

标签 php html simple-html-dom

我正在使用 Php Html Dom Parser 来获取元素。但它不是获取和包含内部文本的元素。看下面的代码;

$html = file_get_html($currentFile);
foreach($html->find('style') as $e){
  echo $e->plaintext;
}

我有这种类型的页面 CSS 代码

<style type="text/css">
ul.gallery li.none { display:none;}
ul.gallery { margin:35px 24px 0 19px;}
</style>
<!--<![endif]-->
<style type="text/css">
body { background:#FFF url(images/bg.gif) repeat-x;}
</style>

我想获取每个元素和带有内部文本的元素。

谢谢

最佳答案

您已经正确定位了 style 标签。但是您需要使用 ->innertext 魔法属性来获取值。考虑这个例子:

include 'simple_html_dom.php';
$html_string = '<style type="text/css">ul.gallery li.none { display:none;}ul.gallery { margin:35px 24px 0 19px;}</style><!--<![endif]--><style type="text/css">body { background:#FFF url(images/bg.gif) repeat-x;}</style>';
$html = str_get_html($html_string); // or file_get_html in your case
$styles = array();
foreach($html->find('style') as $style) {
    $styles[] = $style->innertext;
}

echo '<pre>';
print_r($styles);

$styles 应该输出:

Array
(
    [0] => ul.gallery li.none { display:none;}ul.gallery { margin:35px 24px 0 19px;}
    [1] => body { background:#FFF url(images/bg.gif) repeat-x;}
)

关于Php Html Dom 解析器没有获取 &lt;style&gt; 和 &lt;script&gt; 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24479753/

相关文章:

javascript - 通过简单的html dom删除页面的所有href

php - 简单的 HTML DOM 库

php - MySQL 无法识别 MD5

php - 比较两个 PHP 报告之间的差异

php - 将 php 页面连接到 mySql

javascript - 窗口调整大小时的 jQuery 滚动条不起作用

php - 在 39 个结果后删除 txt 文件中的数据

php - 如何从 Laravel 5.4 中的数据库下载多个图像

php - 如何在加载时在 php 中发布值(无需单击任何内容)

html - Div 不占用全高,因为它的子级锚定有填充