通过 PHP 从 URL 获取 JSON
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31775589/
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
Get JSON from URL by PHP
提问by Mohammad Goldast
I have a URL that returns a JSON object like this:
我有一个返回 JSON 对象的 URL,如下所示:
[
{
"idIMDB": "tt0111161",
"ranking": 1,
"rating": "9.2",
"title": "The Shawshank Redemption",
"urlPoster": "http:\/\/ia.media-imdb.com\/images\/M\/MV5BODU4MjU4NjIwNl5BMl5BanBnXkFtZTgwMDU2MjEyMDE@._V1_UX34_CR0,0,34,50_AL_.jpg",
"year": "1994"
}
]
URL : http://www.myapifilms.com/imdb/top
网址:http: //www.myapifilms.com/imdb/top
I want to get all of the urlPoster
value and set in a array's element, and convert array to JSON so echo it.
我想获取所有urlPoster
值并设置在数组的元素中,并将数组转换为 JSON,以便对其进行回显。
How can I do it through PHP?
我怎样才能通过 PHP 做到这一点?
回答by GitCommit Victor B.
You can do something like that :
你可以这样做:
<?php
$json_url = "http://www.myapifilms.com/imdb/top";
$json = file_get_contents($json_url);
$data = json_decode($json, TRUE);
echo "<pre>";
print_r($data);
echo "</pre>";
?>
回答by Miharbi Hernandez
$json = file_get_contents('http://www.myapifilms.com/imdb/top');
$array = json_decode($json);
$urlPoster=array();
foreach ($array as $value) {
$urlPoster[]=$value->urlPoster;
}
print_r($urlPoster);
回答by arkascha
You can simply decode the json and then pick whatever you need:
您可以简单地解码 json,然后选择您需要的任何内容:
<?php
$input = '[
{
"idIMDB": "tt0111161",
"ranking": 1,
"rating": "9.2",
"title": "The Shawshank Redemption",
"urlPoster": "http:\/\/ia.media-imdb.com\/images\/M\/MV5BODU4MjU4NjIwNl5BMl5BanBnXkFtZTgwMDU2MjEyMDE@._V1_UX34_CR0,0,34,50_AL_.jpg",
"year": "1994"
}
]';
$content = json_decode($input);
$urlPoster = $content[0]->urlPoster;
echo $urlPoster;
The output obviously is the URL stored in that property:
输出显然是存储在该属性中的 URL:
http://ia.media-imdb.com/images/M/MV5BODU4MjU4NjIwNl5BMl5BanBnXkFtZTgwMDU2MjEyMDE@._V1_UX34_CR0,0,34,50_AL_.jpg
http://ia.media-imdb.com/images/M/MV5BODU4MjU4NjIwNl5BMl5BanBnXkFtZTgwMDU2MjEyMDE@._V1_UX34_CR0,0,34,50_AL_.jpg
BTW: "The Shawshank Redemption" is one of the best films ever made...
顺便说一句:“肖申克的救赎”是有史以来最好的电影之一......
回答by aneeshep
This how you do the same thing with array_map function.
这就是你如何用 array_map 函数做同样的事情。
<?php
#function to process the input
function process_input($data)
{
return $data->urlPoster;
}
#input url
$url = 'http://www.myapifilms.com/imdb/top';
#get the data
$json = file_get_contents($url);
#convert to php array
$php_array = json_decode($json);
#process the data and get output
$output = array_map("process_input", $php_array);
#convert the output to json array and print it
echo json_encode($output);