【问题标题】:PHP Simple HTML DOM Parser - Remove Script DataPHP 简单 HTML DOM 解析器 - 删除脚本数据
【发布时间】:2019-09-17 01:32:58
【问题描述】:

我正在使用here 的最新版本。

load() 上调用了一个remove_noise() 函数,它看起来会删除任何脚本数据,这很棒。但是,它似乎不起作用。

在解析 TechCrunch dot com 并查找所有 H2(例如)时,脚本标签中有很多 CDATA。这会使我的 PHP 脚本崩溃,并且会认为 remove_noise() 函数实际上会清除输出。

我是否缺少获得 clean/removed 输出的功能?

【问题讨论】:

标签: php


【解决方案1】:

Sourceforge 上直接向项目请求支持后,事实证明一切都按预期工作,并且正则表达式有一个需要增加的限制。

帮助我解决问题的代码如下:

<?php
// Normal regex doesn't work for such a large script section. The regex parser hits the backtrack limit, so we need to increase it temporarily.
ini_set('pcre.backtrack_limit', '10485760'); // 10MB

// The total file size of the webpage is also much bigger than normally allowed. Use this definition to increase the upper boundary of the parser.
define('MAX_FILE_SIZE', 10485760); // 10MB

include_once 'simple_html_dom.php';
$html = file_get_html('https://techcrunch.com/');

// This will list all headers
foreach($html->find('h2') as $h2) echo $h2->plaintext . PHP_EOL;

// Use this code to remove script tags from the DOM (i.e. if you need to save the DOM for later use. In my tests the file size went down from 1.9MB to 30KB
foreach($html->find('script') as $script) $script->remove();

【讨论】:

    猜你喜欢
    • 2016-07-30
    • 2020-07-16
    • 2012-01-17
    • 1970-01-01
    • 1970-01-01
    • 2014-01-15
    • 2011-08-27
    • 2018-03-05
    相关资源
    最近更新 更多