試圖創建一個呼叫 4 個外部 php 腳本的批處理作業。我可以使用 curl_exec 執行此操作,但是它會等待所有 4 個腳本完成,然后再將文本發送到螢屏。我確信這可以優化,但不能真正讓它作業。有關如何使用 curl_multi_getcontent 輸出緩沖執行此操作的任何建議,以便它顯示從外部站點獲取的資料?
uj5u.com熱心網友回復:
curl_multi 確實。
有關如何使用 curl_multi_getcontent 輸出緩沖執行此操作的任何建議,以便它顯示從外部站點獲取的資料?
好吧,真的沒有必要緩沖它。無論如何,將回應列印到標準輸出是 curl 的默認行為,因此,如果您只想將其列印到終端,則根本不需要添加任何列印代碼:)
$mh=curl_multi_init();
$urls=array(
"url1",
"url2",
"url3",
"url4"
);
$curls=array();
foreach($urls as $url){
$ch=curl_init($url);
curl_multi_add_handle($mh,$ch);
$curls[]=$ch;
}
for(;;){
curl_multi_exec($mh,$active);
if($active<1){
// all downloads finished
break;
}
curl_multi_select($mh);
}
// cleanup
foreach($curls as $ch){
curl_multi_remove_handle($mh,$ch);
curl_close($ch);
}
curl_multi_close($mh);
請注意,這種方法僅在您擁有少量 url 時才是安全的。當您訪問約 100 個或更多 url 時,您可能應該考慮排隊,因此您不會得到 auto-firewall-banned-for-ddos,例如檢查function curl_fetch_multi_2(array $urls_unique, int $max_connections = 100, array $additional_curlopts = null)來自https://gist.github.com/divinity76/ 79efd7b8c0d7849b956cd194659c98e5,該函式永遠不會同時獲取超過$max_connections = 100(可配置,默認100)個url :)
- 編輯:根據評論,如果您出于某種原因想要緩沖輸出,它會變得更加復雜,但您仍然可以這樣做,例如:
<?php
$mh = curl_multi_init();
$urls = array(
"https://example.com",
"https://example.net",
"https://example.org",
);
$curls = array();
foreach ($urls as $url) {
$ch = curl_init($url);
curl_setopt_array($ch, array(
CURLOPT_ENCODING => '',
CURLOPT_RETURNTRANSFER => 1
));
curl_multi_add_handle($mh, $ch);
$curls[(int)$ch] = $ch;
}
while (!empty($curls)) {
for (;;) {
curl_multi_exec($mh, $active);
if ($active < count($curls)) {
// at least 1 download has finished, process it
break;
}
curl_multi_select($mh);
}
while (($info = curl_multi_info_read($mh))) {
if ($info['msg'] !== CURLMSG_DONE) {
continue;
}
$ch = $info['handle'];
$url = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL);
$response = curl_multi_getcontent($ch);
$cap_response = true;
if ($cap_response) {
$response = substr($response, 0, 50);
}
if ($info['result'] !== CURLE_OK) {
echo "Error: {$url}: " . curl_error($ch) . "\n";
}
echo "download finished: " . var_export(["url" => $url, "response" => $response], true) . "\n";
// cleanup
unset($curls[(int)$ch]);
curl_multi_remove_handle($mh, $ch);
curl_close($ch);
}
}
// cleanup
curl_multi_close($mh);
此代碼列印
$ php fuk.php
download finished: array (
'url' => 'https://example.com/',
'response' => '<!doctype html>
<html>
<head>
<title>Example D',
)
download finished: array (
'url' => 'https://example.net/',
'response' => '<!doctype html>
<html>
<head>
<title>Example D',
)
download finished: array (
'url' => 'https://example.org/',
'response' => '<!doctype html>
<html>
<head>
<title>Example D',
)
并行下載 example.com 和 example.net 和 example.org 并緩沖輸出:)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/453301.html
