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

时间:2016-05-18 17:32:05

标签: php curl web-crawler domdocument

我已经在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秒的时间限制,我需要访问相当多的页面(我的主机不允许我更改时间限制)。

能够从页面中只获得一些特定节点或类似的东西会很好。

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

2 个答案:

答案 0 :(得分:1)

耗时部分几乎肯定是HTTP请求。你没办法加快速度。

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

答案 1 :(得分:1)

使用html&#39>对您的数据库进行异步调用。

第一部分

substr_replace()

第二部分

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

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
相关问题