2013-02-16 111 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" 
}