Home  >  Article  >  php教程  >  PHP 使用 CURL 同步抓取多个网页

PHP 使用 CURL 同步抓取多个网页

WBOY
WBOYOriginal
2016-06-21 08:56:54894browse

一般CURL 抓网页的方法, 是一页一页抓, 假设要抓 4页, 所费时间各别是 5,10,7,5 秒, 那全部总合所花的时间就是 5 + 10 + 7 + 5 = 27 秒。若能同时间去抓取多个网页, 所花费的时间 5,10,7,5 秒, 全部总合所花的时间是 10 秒。(花费最多时间的秒数)

于JavaScript 可使用 AJAX 的 async(YAHOO.util.Connect.asyncRequest)来达成, 于 PHP 可以用 CURL 来达成此 Multi-Threading 的效果。

程序(async.php)

以下为引用的内容:
function async_get_url($url_array, $wait_usec = 0)
{
    if (!is_array($url_array))
        return false;

    $wait_usec = intval($wait_usec);

    $data    = array();
    $handle  = array();
    $running = 0;

    $mh = curl_multi_init(); // multi curl handler

    $i = 0;
    foreach($url_array as $url) {
        $ch = curl_init();

        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // return don't print
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);
        curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)');
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); // 302 redirect
        curl_setopt($ch, CURLOPT_MAXREDIRS, 7);

        curl_multi_add_handle($mh, $ch); // 把 curl resource 放进 multi curl handler 里

        $handle[$i++] = $ch;
    }

    /* 执行 */
    do {
        curl_multi_exec($mh, $running);

        if ($wait_usec > 0) /* 每个 connect 要间隔多久 */
            usleep($wait_usec); // 250000 = 0.25 sec
    } while ($running > 0);

    /* 读取资料 */
    foreach($handle as $i => $ch) {
        $content  = curl_multi_getcontent($ch);
        $data[$i] = (curl_errno($ch) == 0) ? $content : false;
    }

    /* 移除 handle*/
    foreach($handle as $ch) {
        curl_multi_remove_handle($mh, $ch);
    }

    curl_multi_close($mh);

    return $data;
}
?>

使用

以下为引用的内容:
$urls = array('http://example1.com', 'http://example2.com');
print_r(async_get_url($urls)); // [0] => example1, [1] => example2
?>

测试

sleep.php # 看时间延长取得的效果

以下为引用的内容:
sleep(intval($_GET['time']));
echo intval($_GET['time']);
?>

以下为引用的内容:
$url_array = array(
        'http://example.com/sleep.php?time=5',
        'http://example.com/sleep.php?time=10',
        'http://example.com/sleep.php?time=7',
        'http://example.com/sleep.php?time=5',
        );
print_r(async_get_url($url_array));
// 总花费时间会是 10 秒, 并印出 [0] => 5, [1] => 10, [2] => 7, [3] => 5
?>



Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn