ここに見られるように、compet.com APIを使用して、ドメインのかなり大きなリストを取得しようとしています。それぞれのランクを照会します-> https://www.compete.com/developer/documentation
私が作成したスクリプトは、入力したドメインのデータベースを取得し、cURLリクエストを開始してWebサイトのランクを競います。各リクエストが一度に1つずつ送信されていたため、これは非常に遅いことにすぐに気付きました。私はいくつかの検索を行い、この投稿に出くわしました-> http://www.phpied.com/simultaneuos-http-requests-in-php-with-curl/は、cURLを使用してPHPで同時HTTPリクエストを実行する方法を説明しています。
残念ながら、そのスクリプトは25,000のドメインの配列を取り、それらすべてを一度に処理しようとします。1,000個のバッチが非常にうまく機能することがわかりました。
1,000個のクエリをcompet.comに送信し、完了を待って、配列が空になるまで次の1,000個を送信する方法はありますか?これまで私が取り組んでいることは次のとおりです。
<?php
//includes
include('includes/mysql.php');
include('includes/config.php');
//get domains
$result = mysql_query("SELECT * FROM $tableName");
while($row = mysql_fetch_array($result)) {
$competeRequests[] = "http://apps.compete.com/sites/" . $row['Domain'] . "/trended/rank/?apikey=xxx&start_date=201207&end_date=201208&jsonp=";
}
//first batch
$curlRequest = multiRequest($competeRequests);
$j = 0;
foreach ($curlRequest as $json){
$j++;
$json_output = json_decode($json, TRUE);
$rank = $json_output[data][trends][rank][0][value];
if($rank) {
//Create mysql query
$query = "Update $tableName SET Rank = '$rank' WHERE ID = '$j'";
//Execute the query
mysql_query($query);
echo $query . "<br/>";
}
}
function multiRequest($data) {
// array of curl handles
$curly = array();
// data to be returned
$result = array();
// multi handle
$mh = curl_multi_init();
// loop through $data and create curl handles
// then add them to the multi-handle
foreach ($data as $id => $d) {
$curly[$id] = curl_init();
$url = (is_array($d) && !empty($d['url'])) ? $d['url'] : $d;
curl_setopt($curly[$id], CURLOPT_URL, $url);
curl_setopt($curly[$id], CURLOPT_HEADER, 0);
curl_setopt($curly[$id], CURLOPT_RETURNTRANSFER, 1);
// post?
if (is_array($d)) {
if (!empty($d['post'])) {
curl_setopt($curly[$id], CURLOPT_POST, 1);
curl_setopt($curly[$id], CURLOPT_POSTFIELDS, $d['post']);
}
}
curl_multi_add_handle($mh, $curly[$id]);
}
// execute the handles
$running = null;
do {
curl_multi_exec($mh, $running);
} while($running > 0);
// get content and remove handles
foreach($curly as $id => $c) {
$result[$id] = curl_multi_getcontent($c);
curl_multi_remove_handle($mh, $c);
}
// all done
curl_multi_close($mh);
return $result;
}
?>