如何在 php 中获取 JSON 数据?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17295957/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get JSON data in php ?
提问by anderskristo
How do I get the data from an JSON object as this with PHP?:
如何使用 PHP 从 JSON 对象中获取数据?:
[
{
"name": "Anders",
},
{
"name": "Chris",
},
{
"name": "Peter",
}
]
This is the PHP code I have:
这是我拥有的 PHP 代码:
$url = 'http://urltotheapi';
$content = file_get_contents($url);
$json = json_decode($content, true);
采纳答案by 472084
foreach($json as $i){
echo $i['name'];
}
回答by Ignacio Vazquez-Abrams
Same as with any other PHP structure.
与任何其他 PHP 结构相同。
echo $json[1]['name'];
回答by Merioles
Note that json_decode converts the json string to an object -- and by specifying the second parameter as true, it will be an (associative) array.
请注意, json_decode 将 json 字符串转换为对象——并且通过将第二个参数指定为 true,它将是一个(关联)数组。
As such, you can then access the data contained within the array like you would a normal array as specified by Ignacio and Jleagle. You can either iterate over the data or display it one by one.
因此,您可以像访问 Ignacio 和 Jleagle 指定的普通数组一样访问数组中包含的数据。您可以遍历数据或一一显示。