curl批处理从官方demo封装

官方demo

// 创建一对cURL资源
$ch1 = curl_init();
$ch2 = curl_init();

// 设置URL和相应的选项
curl_setopt($ch1, CURLOPT_URL, "http://www.example.com/");
curl_setopt($ch1, CURLOPT_HEADER, 0);
curl_setopt($ch2, CURLOPT_URL, "http://www.php.net/");
curl_setopt($ch2, CURLOPT_HEADER, 0);

// 创建批处理cURL句柄
$mh = curl_multi_init();

// 增加2个句柄
curl_multi_add_handle($mh,$ch1);
curl_multi_add_handle($mh,$ch2);

$running=null;
// 执行批处理句柄
do {
    usleep(10000);
    curl_multi_exec($mh,$running);
} while ($running > 0);

// 关闭全部句柄
curl_multi_remove_handle($mh, $ch1);
curl_multi_remove_handle($mh, $ch2);
curl_multi_close($mh);

第一步封装--方法

function multi_post($urls)
{
    // 创建批处理cURL句柄
    $mh = curl_multi_init();

    // 创建一对cURL资源
    // 设置相应的选项
    // 增加句柄
    foreach ($urls as $key => $url) {
        $handles[$key] = curl_init($url);
        curl_setopt($handles[$key], CURLOPT_HEADER, 0);
        curl_multi_add_handle($mh, $handles[$key]);
    }

    $running=null;
    // 执行批处理句柄
    do {
        usleep(10000);
        curl_multi_exec($mh,$running);
    } while ($running > 0);

    // 关闭全部句柄
    foreach ($handles as $key => $handle) {
        curl_multi_remove_handle($mh, $handle);
    }

    curl_multi_close($mh);
}

$urls = array('http://www.shouji.com', 'http://www.baidu.com');
multi_post($urls);

第2次改版--可设置CURL参数

$options = array(
    CURLOPT_RETURNTRANSFER => 1,     // return web page 
    CURLOPT_HEADER => 0,             // don't return headers 
    CURLOPT_TIMEOUT=> 50,           // timeout on response
    CURLOPT_POST   => 1,               // sending post data 
    CURLOPT_POSTFIELDS => $post_data,
);

function multi_post($urls, $options)
{
    // 创建批处理cURL句柄
    $mh = curl_multi_init();

    // 创建一对cURL资源
    // 设置相应的选项
    // 增加句柄
    foreach ($urls as $key => $url) {
        $handles[$url] = curl_init($url);
        curl_setopt_array($handles[$url], $options);
        curl_multi_add_handle($mh, $handles[$url]);
    }

    $running=null;
    // 执行批处理句柄
    do {
        usleep(10000);
        curl_multi_exec($mh,$running);
    } while ($running > 0);

    // 关闭全部句柄
    foreach ($handles as $url => $handle) {
        $result[$url] = curl_multi_getcontent($handle);
        curl_multi_remove_handle($mh, $handle);
    }

    curl_multi_close($mh);

    if (isset($result)) {
        return $result;
    }
    return array();
}
posted @ 2015-01-27 10:11  yo胡yo  阅读(670)  评论(0编辑  收藏  举报