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

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

问题描述

我正在做一个简单的应用程序,从15个不同的URL读取json数据。我有一个特殊的需要,我需要做这个serverly。我使用 file_get_contents($ url)

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).

因为我使用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并行curl请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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