【问题标题】:How to read JSON data using PHP [duplicate]如何使用 PHP 读取 JSON 数据 [重复]
【发布时间】:2016-04-01 16:11:41
【问题描述】:

我正在尝试读取 curl 请求发送的数据,但我无法读取。 例子

curl -x post -d '{user:"test", pwd:"123"}' http://localhost/api/login/

在 PHP 代码中

$user = $_POST['user'];

但我总是得到一个空值,如何解决这个问题?

【问题讨论】:

  • 对不起使用这个json_decode..like print_r(json_decode($curldata))..reference
  • 我试过 json_decode($_POST) 但它也失败了。

标签: php api rest curl


【解决方案1】:

您可以在 curl 中指定帖子名称。现在您正在提交 JSON,但没有名称。 (Link to curl man pages)

-d data={JSON}

然后在php中你可以加载和解码JSON:(Link to json_decode in the php manual)

$data = json_decode($_POST['data'], true);
$user = $data['user'];

如果您想在不使用键/值对的情况下继续发送数据,您可以保留现有的 curl 实现并在 PHP 中使用以下内容:

$data = @file_get_contents("php://input");
$json = json_decode($data, true);

来自:XMLHTTP request passing JSON string as raw post data

【讨论】:

  • 首先感谢您回答我的问题。有没有其他方法可以在不分配变量的情况下读取数据?因为客户希望 api 调用就像我指定的确切方式一样。
  • 我刚刚更新了从 php://input 读取的解决方案,这样您就不需要修改 API 调用
猜你喜欢
  • 2016-09-13
  • 1970-01-01
  • 2018-01-08
  • 2011-08-17
  • 1970-01-01
  • 2020-05-04
  • 2018-07-15
  • 2021-06-25
  • 1970-01-01
相关资源
最近更新 更多