PHP 解码 JSON POST

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14914628/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 08:11:56  来源:igfitidea点击:

PHP decode JSON POST

phpjson

提问by Chris

I"m trying to receive POSTdata in the form of JSON. I'm curling it as:

我正在尝试以POSTJSON 的形式接收数据。我将其卷曲为:

curl -v --header 'content-type:application/json' -X POST --data '{"content":"test content","friends":[\"38383\",\"38282\",\"38389\"],"newFriends":0,"expires":"5-20-2013","region":"35-28"}' http://testserver.com/wg/create.php?action=post

On the PHP side my code is:

在 PHP 方面,我的代码是:

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

    $content    = $data->{'content'};
    $friends    = $data->{'friends'};       // JSON array of FB IDs
    $newFriends = $data->{'newFriends'};
    $expires    = $data->{'expires'};
    $region     = $data->{'region'};    

But even when I print_r ( $data)nothing gets returned to me. Is this the right way of processing a POSTwithout a form?

但即使我print_r ( $data)什么也得不到。这是处理POST没有表格的正确方法吗?

回答by MatsLindh

The JSON data you're submitting is not valid JSON.

您提交的 JSON 数据不是有效的 JSON。

When you use ' in your shell, it will not handle \" as you suspect.

当您在 shell 中使用 ' 时,它不会像您怀疑的那样处理 \"。

curl -v --header 'content-type:application/json' -X POST --data '{"content":"test content","friends": ["38383","38282","38389"],"newFriends":0,"expires":"5-20-2013","region":"35-28"}'

Works as expected.

按预期工作。

<?php
$foo = file_get_contents("php://input");

var_dump(json_decode($foo, true));
?>

Outputs:

输出:

array(5) {
  ["content"]=>
  string(12) "test content"
  ["friends"]=>
  array(3) {
    [0]=>
    string(5) "38383"
    [1]=>
    string(5) "38282"
    [2]=>
    string(5) "38389"
  }
  ["newFriends"]=>
  int(0)
  ["expires"]=>
  string(9) "5-20-2013"
  ["region"]=>
  string(5) "35-28"
}