何年か前のドキュメントが出てきたので一応、書きとめておくよ(「・ω・)「がおー
■コード
以下のようにすることで並列通信を行うことができる。
$i = 0; $ch = array(); $cmh = curl_multi_init(); foreach($urls as $url){ $ch[$i] = curl_init($url); curl_setopt($ch[$i], CURLOPT_RETURNTRANSFER, true); curl_setopt($ch[$i], CURLOPT_FAILONERROR, true); curl_setopt($ch[$i], CURLOPT_TIMEOUT, 10); curl_multi_add_handle($cmh, $ch[$i]); $i++; } // execute $active = null; do{ $mrc = curl_multi_exec($cmh, $active); } while($mrc === CURLM_CALL_MULTI_PERFORM); while($active && $mrc === CURLM_OK){ if(curl_multi_select($cmh) !== false){ do{ $mrc = curl_multi_exec($cmh, $active); } while($mrc === CURLM_CALL_MULTI_PERFORM); } } //read the data from the result in handler if($mrc === CURLM_OK){ for($s = 0; $s < $i; $s++){ if(curl_error($ch[$s]) == ''){// success $contents = curl_multi_getcontent($ch[$s]); } else{ var_dump(curl_error($ch[$s])); } curl_multi_remove_handle($cmh, $ch[$s]); curl_close($ch[$s]); } } curl_multi_close($cmh);
外部のAPIを利用しAPIのレスポンスが低速である場合に特に有用である。但し、同時に開けるソケット数には限りがあるので、接続数がソケット上限数(定数:SOMAXCONN)を超える場合は、上述のロジックを改修する必要がある。