2013-02-16 58 views
8

我“米试图JSON形式接收POST数据我冰壶它:PHP解码JSON POST

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 

在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'};  

但即使当我print_r ($data)什么都没有回到我这是正确的方式处理POST没有表格?

+5

你为什么不使用'json_decode($ _ POST)'? – hohner 2013-02-16 20:11:35

+1

@hohner当我尝试时,它给了我错误'json_decode()期望参数1是字符串,数组给出' – Chris 2013-02-16 20:15:43

+0

@hohner因为'$ _POST'被假定为URL编码数据。 – deceze 2013-02-16 20:16:33

回答

20

您提交的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"}' 

按预期工作。

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

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

输出:

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" 
}