使用PHP CURL抓取网页内容为转载,最近在想使用curl这个库来抓取网页,但目前还没有到那个水平,所以只能看看使用PHP CURL抓取网页这方面的内容了。
<?php
//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;
}
?>
<?php
$urls = array('http://example1.com', 'http://example2.com');
print_r(async_get_url($urls)); // [0] => example1, [1] => example2
?>
<?php //sleep.php sleep(intval($_GET['time'])); echo intval($_GET['time']); ?>
<?php $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 ?>
本文链接:http://www.helpphp.cn/384
原文链接:http://plog.longwin.com.tw/programming/2009/10/07/php-multi-thread-curl-2009