PHP 并行卷曲请求 [英] PHP Parallel curl requests

查看:47
本文介绍了PHP 并行卷曲请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在做一个简单的应用程序,它从 15 个不同的 URL 读取 json 数据.我有一个特殊的需要,我需要在服务器上执行此操作.我正在使用 file_get_contents($url).

因为我使用的是 file_get_contents($url).我写了一个简单的脚本,是不是:

$websites = 数组($url1,$url2,$url3,...$url15);foreach ($websites as $website) {$data[] = file_get_contents($website);}

事实证明它非常慢,因为它等待第一个请求,然后执行下一个请求.

解决方案

如果你的意思是多卷曲,这样的事情可能会有所帮助:

<前><代码>$nodes = array($url1, $url2, $url3);$node_count = count($nodes);$curl_arr = array();$master = curl_multi_init();for($i = 0; $i < $node_count; $i++){$url =$nodes[$i];$curl_arr[$i] = curl_init($url);curl_setopt($curl_arr[$i], CURLOPT_RETURNTRANSFER, true);curl_multi_add_handle($master, $curl_arr[$i]);}做 {curl_multi_exec($master,$running);} while($running > 0);for($i = 0; $i < $node_count; $i++){$results[] = curl_multi_getcontent ( $curl_arr[$i] );}打印_r($结果);

希望对您有所帮助

I am doing a simple app that reads json data from 15 different URLs. I have a special need that I need to do this serverly. I am using file_get_contents($url).

Since I am using file_get_contents($url). I wrote a simple script, is it:

$websites = array(
    $url1,
    $url2,
    $url3,
     ...
    $url15
);

foreach ($websites as $website) {
    $data[] = file_get_contents($website);
}

and it was proven to be very slow, because it waits for the first request and then do the next one.

解决方案

If you mean multi-curl then, something like this might help:


$nodes = array($url1, $url2, $url3);
$node_count = count($nodes);

$curl_arr = array();
$master = curl_multi_init();

for($i = 0; $i < $node_count; $i++)
{
    $url =$nodes[$i];
    $curl_arr[$i] = curl_init($url);
    curl_setopt($curl_arr[$i], CURLOPT_RETURNTRANSFER, true);
    curl_multi_add_handle($master, $curl_arr[$i]);
}

do {
    curl_multi_exec($master,$running);
} while($running > 0);


for($i = 0; $i < $node_count; $i++)
{
    $results[] = curl_multi_getcontent  ( $curl_arr[$i]  );
}
print_r($results);

Hope it helps in some way

这篇关于PHP 并行卷曲请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆