将html文件加载到php脚本的最快方法


Fastest way to load html file to php script

我一直在php上写一个网络爬虫,我使用以下方法:

当前方法

function getPublicationData($url){
    static $seen = array();
    if (isset($seen[$url])) {
        return;
    }
    $seen[$url] = true;
    $cURL = curl_init($url);
    curl_setopt($cURL, CURLOPT_RETURNTRANSFER, true);
    $htmlDoc = curl_exec($cURL);
    $dom= new DOMDocument('1.0');
    libxml_use_internal_errors(true);
    $dom->loadHTML($htmlDoc);
    $dom_xpath = new DOMXPath($dom);
    $strongElements = $dom_xpath->query("//strong[@class='publication-meta-type']");
    foreach( $strongElements as $strongElement){
        echo $strongElement->nodeValue;
    }
}

问题是php有30秒的时间限制,我需要访问相当多的页面(我的主机不允许我更改时间限制)。

如果能够从页面或类似的东西中只获得几个特定的节点,那就太好了。

有人能给我一个解决方案吗?

使用html对数据库进行异步调用。

第一部分

static $seen = array();
if (isset($seen[$url])) {
    return;
}
$seen[$url] = true;
$cURL = curl_init($url);
curl_setopt($cURL, CURLOPT_RETURNTRANSFER, true);
$htmlDoc = curl_exec($cURL);
//save in file, database, whatever

第二部分

创建一个cron作业,或者用另一种方法调用函数来解析数据,并保存在数据库中:

$htmlDoc = //get data from whatever you decided to save
$dom= new DOMDocument('1.0');
libxml_use_internal_errors(true);
$dom->loadHTML($htmlDoc);
$dom_xpath = new DOMXPath($dom);
$strongElements = $dom_xpath->query("//strong[@class='publication-meta-type']");
foreach( $strongElements as $strongElement){
    echo $strongElement->nodeValue;
....

耗时的部分几乎可以肯定是HTTP请求。你不能做太多事情来加快速度。

解决方案?是时候换个新主人了。