使用PHP显示Json数据

时间:2013-11-24 12:42:11

标签: php arrays json

我有一个json文件,我想在PHP文件中显示它的数据。我使用下面的代码,但它给了我错误。

$json = file_get_contents('data.json'); 
$data = json_decode($json);
foreach ($data as $value)
  {
  echo "$value[1]<br>";
  }

data.json 文件包含此格式的数据。

{
"users":[
{"id":"03B7F72C1A522631","user":"test1@gmail.com"}, 
{"id":"27EB9CE8338083AE","user":"test2@gmail.com"}, 
{"id":"E27854ABBFF8CD92","user":"test3@gmail.com"}],
"status":
    {
    "version":"0.9.5.0",
    "command":"listusers",
    "opf":"json",
    "error":false,
    "code":0
    }
}

我希望输出为

User ID | User Email

03B7F72C1A522631 | test1@gmail.com
27EB9CE8338083AE | test2@gmail.com

3 个答案:

答案 0 :(得分:4)

$json = file_get_contents('data.json'); 
$data = json_decode($json,true);
$users=$data['users'];
for($users as $user)
{
   echo $user['id']." ".$user['user'];
}
$status=$data['status'];

答案 1 :(得分:0)

使用它将提供关联数组而不是对象

$data = json_decode($json,true);

有关详细信息,请查看json_decode function

答案 2 :(得分:0)

  

从json文件中获取数据

$homepage = file_get_contents('url');

$someArray = json_decode($homepage, true);

foreach ($someArray as $key => $value) {
    echo "\nAddress: " . $value["address"] . "\n\n";
}