我正在尝试实现一些多cURL函数而不是简单的cURL函数。
我有以下代码段:
$curl = curl_init();
curl_setopt($curl, CURLOPT_ENCODING,'gzip');
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_URL, $url);
$result = curl_exec($curl);
curl_close($curl);
$rv = ($returnArray) ? json_decode($result, true) : json_decode($result);
它给了我结果($ result返回成功和一些数据)。我想重写它以使用curl_multi_init()。我试过这个:
$curl = curl_init();
curl_setopt($curl, CURLOPT_ENCODING,'gzip');
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_URL, $url);
$mh = curl_multi_init();
curl_multi_add_handle($mh,$curl);
$running= \null;
do {
curl_multi_exec($mh,$running);
$result = curl_multi_exec($mh,$running);
} while($running > 0);
curl_multi_remove_handle($mh, $curl);
curl_multi_close($mh);
$rv = ($returnArray) ? json_decode($result, true) : json_decode($result);
我没有结果($ result为空)。我没有任何错误。有什么问题?
答案 0 :(得分:0)
这对我有效:
function get_result( $nodes )
{
$node_count = count($nodes);
$curl_arr = array();
$master = curl_multi_init();
for($i = 0; $i < $node_count; $i++)
{
$url = $nodes[$i];
$curl_arr[$i] = curl_init($url);
curl_setopt($curl_arr[$i], CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl_arr[$i], CURLOPT_CONNECTTIMEOUT, 10);
curl_setopt($curl_arr[$i], CURLOPT_TIMEOUT, 10);
curl_setopt($curl_arr[$i], CURLOPT_ENCODING, "gzip");
curl_setopt($curl_arr[$i], CURLOPT_VERBOSE, true);
curl_setopt($curl_arr[$i], CURLOPT_USERAGENT, 'Mozilla/5.0');
curl_setopt($curl_arr[$i], CURLOPT_FOLLOWLOCATION, true);
curl_setopt($curl_arr[$i], CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
curl_multi_add_handle($master, $curl_arr[$i]);
}
do {
curl_multi_exec($master,$running);
curl_multi_select($master, 5.0);
} while($running > 0);
$output = "";
for($i = 0; $i < $node_count; $i++)
{
$output .= curl_multi_getcontent( $curl_arr[$i] ) . "<breaktag>";
curl_multi_remove_handle( $master, $curl_arr[$i] );
curl_close( $curl_arr[$i] );
}
curl_multi_close( $master );
return $output;
}
$nodes[] = () // your URLs
$responses = get_result( $nodes );
$responses = explode("<breaktag>", $responses); //now responses is array of result