gpt4 book ai didi

php - 使用 cURL 在 PHP 中同时发出 HTTP 请求

转载 作者:行者123 更新时间:2023-12-02 22:30:20 26 4
gpt4 key购买 nike

我正在尝试获取一个相当大的域列表,使用 compete.com API 查询每个域的排名,如此处所示 -> https://www.compete.com/developer/documentation

我编写的脚本采用我填充的域数据库并启动 cURL 请求以竞争网站的排名。我很快意识到这非常慢,因为每个请求都是一次发送一个。我做了一些搜索并发现了这篇文章-> http://www.phpied.com/simultaneuos-http-requests-in-php-with-curl/其中解释了如何使用 cURL 在 PHP 中同时执行 HTTP 请求。

不幸的是,该脚本将采用 25,000 个域的数组并尝试一次处理所有域。我发现每批 1,000 个效果很好。

知道如何向 compete.com 发送 1,000 个查询然后等待完成并发送下一个 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;

}
?>

最佳答案

代替

//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++;
// ...

这会将大数组分成 1,000 个 block ,并将这 1,000 个值传递给您的 multiRequest 函数,该函数使用 cURL 来执行这些请求。

关于php - 使用 cURL 在 PHP 中同时发出 HTTP 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12379801/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com