在PHP代码中使用远程json文件

时间:2015-03-12 05:44:56

标签: php json

为了获得有关" ID"的详细信息,我准备了以下带有json数组的PHP。它工作得很好。

<?php
$json = '{"records": 
       [
         {"Name":"Jhon", "Age":"45", "id":"101"},
         {"Name":"Bhil", "Age":"42", "id":"102"},
         {"Name":"Tone", "Age":"41", "id":"103"},
       ]
    }';

$myjson = json_decode($json, true);  
  foreach ( $myjson['records'] as $row ) {  
                        if ($row['id'] =='216') { 
                         echo 'Details of  login id:&nbsp;'.  $row['id']. '<br/>';
                         foreach ( $row as $field => $value ) {  // loop the fields
                               // do the work here
                             }
                   }
         }
?>

现在,对于我的一个项目,我必须用各种各样的vaules创造750个ID。 将所有这些放在php文件中可能会减慢页面加载速度。

因此,我发了json文件(远程): xyz.com/dir/jsondata.json

请指导我,如何在php代码中输入上述json文件。

2 个答案:

答案 0 :(得分:0)

使用$data=file_get_contents('xyz.com/dir/jsondata.json');获取文件,然后使用解码json并循环遍历

$myjson = json_decode($data, true);  
  foreach ( $myjson['records'] as $row ) {  
                        if ($row['id'] =='216') { 
                         echo 'Details of  login id:&nbsp;'.  $row['id']. '<br/>';
                         foreach ( $row as $field => $value ) {  // loop the fields
                               // do the work here
                             }
                   }
         }

答案 1 :(得分:0)

file_get_contents()正是您要找的。它会将文件的全部内容放入一个字符串中。

$json = file_get_contents('dir/jsondata.json');