【问题标题】:How to get the JSON string POSTed to a REST API using PHP?如何使用 PHP 将 JSON 字符串发布到 REST API?
【发布时间】:2016-03-25 12:13:32
【问题描述】:

我正在使用 curl 将 JSON 字符串发布到用 PHP 开发的 API,但我无法在 webservice 方法中获取 JSON 字符串。

这是我使用 curl 的客户:

$data = array("name" => "prachi", "age" => "24");                                                                    
$data_string = json_encode($data);                                                                                   

$ch = curl_init('http://server.com/rest/users');                                                                      
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");                                                                     
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);                                                                  
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);                                                                      
curl_setopt($ch, CURLOPT_HTTPHEADER, array(                                                                          
    'Content-Type: application/json',                                                                                
    'Content-Length: ' . strlen($data_string))                                                                       
);                                                                                                                   

$result = curl_exec($ch);

这里,rest 是控制器类的名称,user 是其中的动作。那么,在user 方法中,如何获取JSON 字符串呢?

【问题讨论】:

  • 你得到什么错误?

标签: php mysql json rest curl


【解决方案1】:

使用 $_POST 获取您的字符串,即 $_POST['name'] 和 $_POST['age']

将 curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST") 替换为 curl_setopt($ch, CURLOPT_POST, 1);

【讨论】:

    猜你喜欢
    • 2015-10-14
    • 2016-08-02
    • 2016-02-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-13
    相关资源
    最近更新 更多