【问题标题】:Get JSON from URL by PHP通过 PHP 从 URL 获取 JSON
【发布时间】:2015-10-24 20:51:52
【问题描述】:

我有一个返回 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"
    }
]

网址:http://www.myapifilms.com/imdb/top

我想获取所有的 urlPoster 值并设置在数组的元素中,然后将数组转换为 JSON 以便回显它。

我如何通过 PHP 做到这一点?

【问题讨论】:

  • 你试过json_decode()吗?

标签: php json getjson


【解决方案1】:

你可以这样做:

<?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>";
?>

【讨论】:

    【解决方案2】:
    $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);
    

    【讨论】:

      【解决方案3】:

      您可以简单地解码 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;
      

      输出显然是存储在该属性中的 URL:

      http://ia.media-imdb.com/images/M/MV5BODU4MjU4NjIwNl5BMl5BanBnXkFtZTgwMDU2MjEyMDE@._V1_UX34_CR0,0,34,50_AL_.jpg

      顺便说一句:“肖申克的救赎”是有史以来最好的电影之一……

      【讨论】:

        【解决方案4】:

        这就是你使用 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);
        

        【讨论】:

          猜你喜欢
          • 2015-05-13
          • 2017-05-23
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2016-08-06
          • 2017-06-03
          相关资源
          最近更新 更多