我有一个简单的任务。 从页面中获取所有文章,以及获取每篇文章的所有图片。PHP简单的HTML DOM解析器:获取所有文章
今天,我决定用PHP Simple HTML DOM Parse
举个例子,我用下面的代码:
<?php
include("simple_html_dom.php");
$sitesToCheck = array(
array(
'url' => 'http://googleblog.blogspot.ru/',
'search_element' => 'h2.title a',
'get_element' => 'div.post-content'
),
array(
// 'url' => '', // Site address with a list of of articles
// 'search_element' => '', // Link of Article on the site
// 'get_element' => '' // desired content
)
);
$s = microtime(true);
foreach($sitesToCheck as $site)
{
$html = file_get_html($site['url']);
foreach($html->find($site['search_element']) as $link)
{
$content = '';
$savePath = 'cachedPages/'.md5($site['url']).'/';
$fileName = md5($link->href);
if (! file_exists($savePath.$fileName))
{
$post_for_scan = file_get_html($link->href);
foreach($post_for_scan->find($site["get_element"]) as $element)
{
$content .= $element->plaintext . PHP_EOL;
}
if (! file_exists($savePath) && ! mkdir($savePath, 0, true))
{
die('Unable to create directory ...');
}
file_put_contents($savePath.$fileName, $content);
}
}
}
$e = microtime(true);
echo $e-$s;
我会尽量只得到文章没有图片。但是,我从服务器获取
响应“120秒最长执行时间超过了”
。
请向我解释,我做错了什么......
告诉我,有没有其他的办法让所有的每个项目具体地址在文章的所有照片?
这么多的 “简单” 的一部分,诶。 :)尽管如此,上次我检查过它(几个月前),simple_html_dom仍然是一堆热气腾腾的东西。 DOMDocument + DOMXPath占用了空间和时间的1/5。从字面上看。通过消除它,我减少了80%的内存使用量和运行时间。 – cHao
你不应该过分依赖这个,但是如果你事先知道一个过程需要很长时间,试试'set_time_limit(0)',但是在任何地方使用它都不是一个好习惯。如果超过最大执行时间(在你的情况下为120秒),那么这将阻止php杀死你的进程,并且它会一直运行直到它结束。问题是......如果你在程序中犯了一个错误,导致永远运行,你的程序将在服务器上占用资源,直到采取手动操作。 – ILikeTacos
就这样,我听起来不像一个狂热的仇敌,有一件事simple_html_dom可能会有好处。如果你的HTML损坏严重,不再看起来像HTML,那么DOMDocument可能无法很好地处理它。像simple_html_dom *这样的lib可能会更好地处理这种垃圾,因为它的设计与古怪的标记一起工作。但是很少有必要解析一个非常糟糕的文档,DOMDocument无法处理它。至少,我从来没有处理过它。 – cHao