我正在尝试使用compete.com API查询一个相当大的域列表,每个域的排名如下所示->https://www.compete.com/developer/documentation
我编写的脚本获取了我填充的域的数据库,并启动了一个cURL请求来竞争网站的排名。我很快意识到这很慢,因为每个请求都是一次发送一个。我搜索了一下,发现了这篇文章->http://www.phpied.com/simultaneuos-http-requests-in-php-with-curl/它解释了如何用cURL在PHP中同时执行HTTP请求。
不幸的是,该脚本将占用25000个域的阵列,并尝试同时处理所有域。我发现1000个批次的效果很好。
知道如何向compete.com发送1000个查询,然后等待完成并发送下一个1000,直到数组为空吗 以下是我目前正在处理的内容:
<?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;
}
?>
而不是
//first batch
$curlRequest = multiRequest($competeRequests);
$j = 0;
foreach ($curlRequest as $json){
你可以做:
$curlRequest = array();
foreach (array_chunk($competeRequests, 1000) as $requests) {
$results = multiRequest($requests);
$curlRequest = array_merge($curlRequest, $results);
}
$j = 0;
foreach ($curlRequest as $json){
$j++;
// ...
这将把大数组拆分为1000个块,并将这1000个值传递给multiRequest
函数,该函数使用cURL来执行这些请求。
https://github.com/webdevelopers-eu/ShadowHostCloak
这正是你想要的。只需将空参数传递给new Proxy()
即可绕过代理并发出直接请求。
您可以在其中填充1000个请求并调用$proxy->execWait()
,它将同时处理所有请求,并在所有操作完成后退出该方法。。。然后你可以重复。