CURL无法在代码中找到错误

时间:2014-04-16 06:50:24

标签: php json curl

<?php
    $ch = curl_init("URL");
    $username = "USERNAME";
    $password = "PASSWORD";
    $fields = array("from"=>array("name"=>"Bob","city"=>"SAINT-LAURENT","country"=>"CA","state"=>"QC","postal_code"=>"H4R1W4"),"to"=>array("is_commercial"=>true,"city"=>"ANJOU","country"=>"CA","state"=>"QC","postal_code"=>"H1J1Z4"),"packages"=>array("units"=>"imperial","type"=>"package","items"=>array("width"=>1,"height"=>2,"length"=>3,"weight"=>4)));
    curl_setopt($ch,CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
    curl_setopt($ch, CURLOPT_USERPWD, $username . ":" . $password);
    curl_setopt($ch,CURLOPT_POSTFIELDS, json_encode($fields));        
    $data = curl_exec($ch);
    if ($data === FALSE) 
    { 
        $temp=curl_error($ch);
        echo "<p>cURL Error: {$temp}</p>";
    }
    echo "<pre>";
    print_r($data);
    curl_close($ch);
?>

我得到的错误是

  {"error": "Unexpected input. Please make sure this is a valid JSON document"}

我无法理解这意味着什么 更新后我得到的错误是
传递给Support \ ExposedObjectAbstract :: setFromArray()的参数1必须是类型数组,给定整数,在第22行的Shipping / Packages.php中调用并定义

3 个答案:

答案 0 :(得分:1)

您的服务器端点(您正在调用的URL)要求输入是有效的JSON。为此,您可以替换:

$field_string = http_build_query($fields);

使用:

$field_string = json_encode($fields);

答案 1 :(得分:1)

首先设置您要发送的HTTP标头JSON

curl_setopt($ch,CURLOPT_HTTPHEADER, array('Content-Type: application/json'));

然后,将您的数组转换为JSON,然后设置为postfields

curl_setopt($ch,CURLOPT_POSTFIELDS, json_encode($fields));

答案 2 :(得分:0)

$ field_string = http_build_query($ fields);问题是什么,尝试传递为数组

curl_setopt($ch,CURLOPT_POSTFIELDS,$fields);