【问题标题】:Usage of json_encode and json_decodejson_encode 和 json_decode 的使用
【发布时间】:2011-12-08 13:52:27
【问题描述】:

我是 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

但是,我收到如下错误:

试图获取非对象的属性。

【问题讨论】:

  • $data是什么变量?尝试转储它:var_dump($data)
  • @Jorge 我试过了。将结果设为 null。
  • @Jorge,我正在获取 html 数据以及 json 编码数据。是因为使用了exit还是file_get_contents?
  • localhost/file1.php 输出的数据是否正确?正如@nickb 在下面的 cmets 中提到的,脚本可能没有得到正确的 JSON。
  • 发布您问题中的所有输出。特别是您从 file1.php 获得的输出(显示 HTML,然后显示 JSON)。

标签: php json api file-get-contents


【解决方案1】:

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

使用这个:

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

【讨论】:

  • 应该 - 如果不是,那么您的原始数组不包含 name 键(或者您的脚本没有提取正确的 JSON)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-05-03
  • 1970-01-01
  • 1970-01-01
  • 2018-11-05
  • 1970-01-01
  • 1970-01-01
  • 2012-03-08
相关资源
最近更新 更多