1

Safari 有一个“阅读器模式”,它可以从网站中删除除文本之外的所有内容。

现在我需要从站点获取 HTML 源代码,然后使用PHP获取真实的内容新闻,例如 Safari 的“阅读器模式” !你能帮助我吗??:S

4

1 回答 1

1

有人指出,简单地发布另一个帖子的链接并不是很有帮助,所以我正在更新。从那以后,我开始使用 Arc90 可读性的 PHP 端口,它工作得非常好。

这是 Readability.js 的 PHP 端口的链接:http: //www.keyvan.net/2010/08/php-readability/

下面是一个简单的实现示例:

$url = 'http://';
$html = file_get_contents($url);

if (function_exists('tidy_parse_string')) {
    $tidy = tidy_parse_string($html, array(), 'UTF8');
    $tidy->cleanRepair();
    $html = $tidy->value;
}

// give it to Readability
$readability = new Readability($html, $url);
// echo $readability->html;
// echo htmlspecialchars($tidy($readability->html, true));

// print debug output?
// useful to compare against Arc90's original JS version -
// simply click the bookmarklet with FireBug's console window open
$readability->debug = false;
// convert links to footnotes?
$readability->convertLinksToFootnotes = false;

$readability->lightClean = false;
// $readability->revertForcedParagraphElements = false;

// process it
$result = $readability->init();
// store reference to dom content processed by Readability
$content = $readability->getContent();

echo '<h1>'.$readability->getTitle()->textContent.'</h1>';
echo $content->innerHTML;

在上面展开

如果你想打开这个工作的页面数量,我发现你可以在传递给 Readability 之前 curl 并为 html 定义用户代理,你会得到更好的结果。加入一些重定向跟踪,它甚至更好。

这是我使用的函数,而不是 file_get_contents:

function getData($url) {
    $url = str_replace('&amp;', '&', urldecode(trim($url)) );
    $timeout = 5;
    $cookie = tempnam('/tmp', 'CURLCOOKIE');
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows; U; Windows NT 5.1; rv:1.7.3) Gecko/20041001 Firefox/0.10.1');
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($ch, CURLOPT_ENCODING, '');
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_AUTOREFERER, true);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
    curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
    curl_setopt($ch, CURLOPT_MAXREDIRS, 10);
    $content = curl_exec($ch);
    curl_close ($ch);
    return $content;
}

执行:

$url = 'http://';
//$html = file_get_contents($url);
$html = getData($url);

if (function_exists('tidy_parse_string')) {
    $tidy = tidy_parse_string($html, array(), 'UTF8');
    $tidy->cleanRepair();
    $html = $tidy->value;
}

$readability = new Readability($html, $url);

//...
于 2014-02-03T21:11:05.933 回答