我一直面临这个问题,我有4个api来处理并输出到最终的网页。当我这样做时,我的网页加载时间超过一分钟。经过长时间的思考,我发现我正在同时打电话。我需要异步调用以避免延迟。然后我最终得到了这里没有返回网页上任何数据的代码。帮帮我! 。我从http://php.net/manual/en/function.curl-multi-exec.php获得了此代码
// set URL and other appropriate options
curl_setopt($ch1, CURLOPT_URL, "http://example1.com");
curl_setopt($ch1, CURLOPT_POST, 1);
curl_setopt($ch1, CURLOPT_POSTFIELDS,"x=a&y=b");
curl_setopt($ch1, CURLOPT_HEADER, 0);
curl_setopt($ch2, CURLOPT_URL, "http://www.example2.com"."m=c&n=d");
curl_setopt($ch2, CURLOPT_HEADER, 0);
curl_setopt($ch2, CURLOPT_RETURNTRANSFER, true);
//create the multiple cURL handle
$mh = curl_multi_init();
//add the two handles
curl_multi_add_handle($mh,$ch1);
curl_multi_add_handle($mh,$ch2);
$active = null;
//execute the handles
do {
$mrc = curl_multi_exec($mh, $active);
} while ($mrc == CURLM_CALL_MULTI_PERFORM);
while ($active && $mrc == CURLM_OK) {
if (curl_multi_select($mh) != -1) {
do {
$mrc = curl_multi_exec($mh, $active);
} while ($mrc == CURLM_CALL_MULTI_PERFORM);
}
}
//close the handles
curl_multi_remove_handle($mh, $ch1);
curl_multi_remove_handle($mh, $ch2);
curl_multi_close($mh);
echo $mrc;
?>
我有4个api,其中2个是POST请求,2个是GET。 提前致谢