PHP解码JSON POST

Chr*_*ris 9 php json

我试图以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
Run Code Online (Sandbox Code Playgroud)

在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'};    
Run Code Online (Sandbox Code Playgroud)

但即使我print_r ( $data)什么都没有归还给我.这是处理POST没有表格的正确方法吗?

Mat*_*ndh 25

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

当您在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"}'
Run Code Online (Sandbox Code Playgroud)

按预期工作.

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

var_dump(json_decode($foo, true));
?>
Run Code Online (Sandbox Code Playgroud)

输出:

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"
}
Run Code Online (Sandbox Code Playgroud)