【问题标题】:PHP Extract Values from JSON Array for REST API [duplicate]PHP从用于REST API的JSON数组中提取值[重复]
【发布时间】:2021-11-09 09:10:03
【问题描述】:

您好,我正在开发一个简单的通用 REST API,以从 JSON POST 调用中读取名字和电子邮件地址,我正在使用示例测试 POST 将这些值传递给脚本。

{
    "fname": "Viktor",
    "email": "sample@emailhere.net"
}

这是代码

$json = file_get_contents('php://input');
$data = json_decode($json);
print_r ($data);

它工作正常并返回

stdClass Object ( [fname] => Ram [email] => Ram@gmail.com )

...但是当我尝试从 $data 中提取特定元素时,它返回 500 服务器错误 - 即我添加了这 3 行

$email = $data[0]["email"];
$fname = $data[0]["fname"];
print "email: $email fname: $fname";

提取这个简单 JSON 的正确语法是什么?

【问题讨论】:

    标签: php arrays api rest


    【解决方案1】:

    您的 JSON 不是数组。另外,json_decode 默认返回对象,您需要将其设置为关联数组模式。正确的代码将是

    $json = file_get_contents('php://input');
    $data = json_decode($json, true);
    $email = $data["email"];
    $fname = $data["fname"];
    print "email: $email fname: $fname";
    

    【讨论】:

      猜你喜欢
      • 2012-10-07
      • 2015-08-30
      • 1970-01-01
      • 1970-01-01
      • 2023-04-04
      • 2019-12-06
      • 2014-03-07
      • 1970-01-01
      • 2017-09-10
      相关资源
      最近更新 更多