【问题标题】:Cant access JSON data with PHP无法使用 PHP 访问 JSON 数据
【发布时间】:2021-12-07 18:31:49
【问题描述】:

我试图从这个 JSON 访问 ID 和 SENT,但对我不起作用。

更新

$json = '{
 "response": {
  "sent": true,
  "message": "Sent to 57304",
  "id": "gBEGVzBChXFYAgmcOrfFpGem8qw"
 }
}';

json_decode($json);

$id=$json->id;
$sent=$json->sent;

echo "</br> id:".$id."</br>";
echo "</br> sent:".$sent."</br>";

【问题讨论】:

  • 你需要将json字符串包裹在json_decode()
  • @mulquin 刚刚更新,但仍无法使用 json_decode()
  • 下次你可以 var_export($json) 看看它有什么并发现你的错误。这就是调试方式。

标签: php json


【解决方案1】:

使用 php json_decode() 函数。像这样:

$json = '{
   "response": {
   "sent": true,
   "message": "Sent to 57304",
   "id": "gBEGVzBChXFYAgmcOrfFpGem8qw"
   }
}';

$json = json_decode($json, true);
$json = (object) $json['response'];
echo $json->sent;  // output: 1
echo $json->id;    // output: "gBEGVzBChXFYAgmcOrfFpGem8qw"

1 等价于布尔值 true

【讨论】:

  • 非常感谢这项工作!
  • 什么都没有发生,我很高兴它对你有用。 @Andres Carvajal
【解决方案2】:

它的工作原理,JSON对象有两个标签,所以你不能直接访问内部对象。您应该将 json_decode($json) 分配给一个 php 对象,例如 $obj=json_decode($json);这是工作文件

<?php
$json = '{
        "response": {
                    "sent": true,
                    "message": "Sent to 57304",
                    "id": "gBEGVzBChXFYAgmcOrfFpGem8qw"
                    }
        }';
   // convert assign json data into php object
   $obj=json_decode($json);
   //All the inner key can be access throug 'response' object
   $id=$obj->response->id;
   $sent=$obj->response->sent;
   
   
   echo "</br> id:".$id."</br>";
   echo "</br> sent:".$sent."</br>";

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-15
    相关资源
    最近更新 更多