使用json_encode和json_decode

时间:2011-12-08 13:52:28

标签: php json api file-get-contents

我是PHP的新手。我使用json_encode将数组转换为json数据,并使用另一个文件中的json_decode对其进行解码。但是,我得到json错误作为语法错误。

我的代码如下:

文件1:

$result = get_data_array();

exit(json_encode($result));

文件2:

$result = file_get_contents("http://localhost/file1.php");
$data = json_decode($result,true);

$data->name // name is the array key

但是,我收到的错误是:

  

尝试获取非对象的属性。

1 个答案:

答案 0 :(得分:3)

您将true传递给json_decode的第二个参数,因此它将返回一个数组。

使用此:

$result = file_get_contents("http://localhost/file1.php"); 
$data = json_decode($result,true);
echo $data['name'];