Reading JSON POST using PHP

前端 未结 3 1135
予麋鹿
予麋鹿 2020-11-22 02:18

I looked around a lot before posting this question so my apologies if it is on another post and this is only my second quesiton on here so apologies if I don\'t format this

3条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2020-11-22 02:45

    You have empty $_POST. If your web-server wants see data in json-format you need to read the raw input and then parse it with JSON decode.

    You need something like that:

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

    Also you have wrong code for testing JSON-communication...

    CURLOPT_POSTFIELDS tells curl to encode your parameters as application/x-www-form-urlencoded. You need JSON-string here.

    UPDATE

    Your php code for test page should be like that:

    $data_string = json_encode($data);
    
    $ch = curl_init('http://webservice.local/');
    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);
    $result = json_decode($result);
    var_dump($result);
    

    Also on your web-service page you should remove one of the lines header('Content-type: application/json');. It must be called only once.

提交回复
热议问题