Reputation: 33
<?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 I got is
{"error": "Unexpected input. Please make sure this is a valid JSON document"}
I'm unable to understand what this meant .
After Update the error i get is
Argument 1 passed to Support\ExposedObjectAbstract::setFromArray() must be of the type array, integer given, called in Shipping/Packages.php on line 22 and defined
Upvotes: 0
Views: 82
Reputation: 39355
First set the HTTP header that you are sending JSON
curl_setopt($ch,CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
And then, convert your array into JSON
, and then setting to postfields
curl_setopt($ch,CURLOPT_POSTFIELDS, json_encode($fields));
Upvotes: 1
Reputation: 54212
Your server end point (the URL you're calling) requires the input to be a valid JSON. In order to do this, you can replace:
$field_string = http_build_query($fields);
with:
$field_string = json_encode($fields);
Upvotes: 1
Reputation: 1160
$field_string = http_build_query($fields); is what the problem is , try to pass as array
curl_setopt($ch,CURLOPT_POSTFIELDS,$fields);
Upvotes: 0