gpt4 book ai didi

php - 如何使用 cURL 立即打开多个 URL

转载 作者:可可西里 更新时间:2023-11-01 01:13:53 25 4
gpt4 key购买 nike

我想知道是否可以使用 cURL 或其他方式打开多个 URL。

到目前为止,我一直在尝试这个。

$urls = array(
"http://google.com",
"http://youtube.com",
);

foreach($urls as $url) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT,0);
curl_setopt($ch, CURLOPT_TIMEOUT_MS, 200);
curl_exec($ch);
curl_close($ch);
}

200 毫秒是为了让网站完全打开。也许您知道任何替代方案。

是否可以在 PHP 中同时打开多个 URL?不是客户端,是服务器端。

最佳答案

您的解决方案是同时进行 cURL HTTP 请求。
为了更快地实现,您可以使用此功能(感谢 phpied ):

function multiRequest($data, $options = array()) {

// 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']);
}
}

// extra options?
if (!empty($options)) {
curl_setopt_array($curly[$id], $options);
}

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;
}

然后像这样使用它:

$data = array(
'http://search.yahooapis.com/VideoSearchService/V1/videoSearch?appid=YahooDemo&query=Pearl+Jam&output=json',
'http://search.yahooapis.com/ImageSearchService/V1/imageSearch?appid=YahooDemo&query=Pearl+Jam&output=json',
'http://search.yahooapis.com/AudioSearchService/V1/artistSearch?appid=YahooDemo&artist=Pearl+Jam&output=json'
);
$r = multiRequest($data);

echo '<pre>';
print_r($r);

希望对您有所帮助。
还有 read this .

关于php - 如何使用 cURL 立即打开多个 URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45172202/

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