2013-10-03 62 views
3

我有一个JSON发送到一个REST API此卷曲功能:通过PHP REST API检索JSON

$url = "https://server.com/api.php"; 
$fields = array("method" => "mymethod", "email" => "myemail"); 

$result = sendTrigger($url, $fields); 

function sendTrigger($url, $fields){ 
    $fields = json_encode($fields); 
    $ch = curl_init(); 
    curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/json; charset=UTF-8")); 
    curl_setopt($ch, CURLOPT_URL, $url); 
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); 
    curl_setopt($ch, CURLOPT_POSTFIELDS, $fields); 
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 
    $curlResult["msg"] = curl_exec($ch); 
    $curlResult["http"] = curl_getinfo($ch, CURLINFO_HTTP_CODE); 
    curl_close($ch); 
    return $curlResult; 
} 

在服务器上,我有这样的代码:

$data = json_decode($_REQUEST); 
var_dump($data); 
exit(); 

当我执行卷曲命令它返回我这个:

Warning: json_decode() expects parameter 1 to be string, array given in 

那是怎么回事?

谢谢。

+0

混了'和'json_decode' json_encode'? – Brian

+1

可能重复的[如何在PHP中获取POST的主体?](http://stackoverflow.com/questions/8945879/how-to-get-body-of-a-post-in-php) – Quentin

+3

因为' $ _REQUEST'通常是一个数组,即使是空的。你的JSON blob不会出现在那里,但是'php:// input'。 – mario

回答

8

如果您未使用表单编码的内容类型之一,PHP将不会将数据填充到$_POST

您需要从PHP原始输入让你的JSON有效载荷是这样的:

$json = file_get_contents('php://input'); 
$array = json_decode($json); 
0

在PHP json_decode接受一个字符串并将其转换为一个对象。 $_REQUEST变量是一个全局变量,其中包含$_GET,$_POST$_COOKIE(请参阅PHP reference)的内容。很可能,您的代码中存在打字错误,您可能打算使用$request而不是$_REQUEST