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


using remote json file in php code

为了获得有关"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 Ids 周围克里特。将所有这些放在php文件中可能会减慢页面加载速度。

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

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

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

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

$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
                             }
                   }
         }