PHP curl post解析错误

时间:2015-06-20 19:16:54

标签: php curl

我正在尝试通过POST发送数据。

这是我做过的事情

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL,"https://lc-api.sdl.com/translate");
    $headers = array();
    $headers[] = 'Content-type:application/json';
    $headers[] = 'Authorization:LC apiKey=QidCWRGQ%2BHsdzGE6rrBgiw%3D%3D';

    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS,"text=Bonjour&from=fra&to=eng");  //Post Fields
    $server_output = curl_exec ($ch);

   curl_close ($ch);

   print  $server_output ;    

我收到错误消息

Error parsing json at column:6 line:1 offset:-1

这是工作卷曲请求

  curl -X POST -H "Content-type: application/json" -H "Authorization: LC apiKey=QidCWRGQ%2BHsdzGE6rrBgiw%3D%3D" -d '{"text":"Bonjour", "from" : "fra", "to" : "eng"}' https://lc-api.sdl.com/translate

2 个答案:

答案 0 :(得分:2)

尝试如下:

<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,"https://lc-api.sdl.com/translate");
$headers = array();
$headers[] = 'Content-type:application/json';
$headers[] = 'Authorization:LC apiKey=QidCWRGQ%2BHsdzGE6rrBgiw%3D%3D';

$data = array("text" => "Bonjour", "from" => "fra", "to" => "eng");
$data_string = json_encode($data);

curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS,$data_string);  //Post Fields
$server_output = curl_exec ($ch);

curl_close ($ch);

print  $server_output ;
?>

json_encode格式发布字段。

答案 1 :(得分:0)

添加:

 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);

完整代码:

<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,"https://lc-api.sdl.com/translate");
$headers = array();
$headers[] = 'Content-type:application/json';
$headers[] = 'Authorization:LC apiKey=QidCWRGQ%2BHsdzGE6rrBgiw%3D%3D';

$data = array("text" => "Bonjour", "from" => "fra", "to" => "eng");
$data_string = json_encode($data);

curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

curl_setopt($ch, CURLOPT_POSTFIELDS,$data_string);  //Post Fields
$server_output = curl_exec ($ch);

curl_close ($ch);

var_dump($server_output );
?>