多个curl json和json打印 [英] Multiple curl json and json print
问题描述
我想通过curl访问多个URL并打印子输出。我已经看到了:多个cURL并输出JSON?,但我无法使其正常工作...
I want to access multiples urls via curl and print the son output. I've seen this: multiple cURL and output JSON? but I`am not able make it work anyway...
我的代码:
<?php
$urls = Array(
'URLtoJSON1',
'URLtoJSON1'
);
for($i = 0; $i < 3; $i++) {
$curl[$i] = curl_init($urls);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($curl, CURLOPT_USERPWD, "YYY:XXX");
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $curl_post_data);
$curl_response[$i] = curl_exec($curl);
curl_close($curl);
$data = json_decode($curl_response[$i]);
$name[$i] = $data->fullDisplayName;
$datum[$i] = $data->timestamp;
$result[$i] = $data->result;
}
// here I`d love to be able echo output $name[URLtoJSON], etc...
?>
感谢您的帮助。
推荐答案
您可以创建一个 foreach
循环,而不是执行 for
循环通过执行 foreach($ urls为$ key => $ url)
遍历 $ urls
数组。 $ key
将保存数组的索引(从0开始),而 $ url
将保存URL。
Instead of doing a for
loop, you can make a foreach
loop that iterates over your $urls
array by doing foreach ($urls as $key=>$url)
. $key
will hold the index of the array (starting at 0) and $url
will hold the URL.
结果代码如下:
$urls = Array(
'URLtoJSON1',
'URLtoJSON2'
);
foreach ($urls as $key=>$url) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_USERPWD, "YYY:XXX");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $ch_post_data);
$ch_response = curl_exec($ch);
curl_close($ch);
$data = json_decode($ch_response);
$name[$key] = $data->fullDisplayName;
$datum[$key] = $data->timestamp;
$result[$key] = $data->result;
}
现在,如果要访问 $ name , code>第一个URL,您只需执行
$ echo $ name [0];
Now if you want to access $name
of the first URL, you would just do $echo $name[0];
您也可以通过类似的方式访问 $ datum
或 $ result
。
You can also access $datum
or $result
in a similar way.
这篇关于多个curl json和json打印的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!