Reputation:
I have an api link which is working fine on terminal. I wand to use same api link to retrieve data using CURL in php. I tried below code:
<?php
// set up the curl resource
$ch = curl_init();
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
//curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, 'urlxxxxx');
// execute the request
$output = curl_exec($ch);
// output the profile information - includes the header
echo "curl response is : <br> ".($output). PHP_EOL;
// close curl resource to free up system resources
curl_close($ch);
?>
but I am getting response as :
curl response is : { "error" : "JSON syntax error: malformed JSON string, neither array, object, number, string or atom, at character offset 0 (before \"(end of string)\") at /usr/share/perl5/JSON.pm line 171.\n" }
I am new to CURL guide me regarding the issue for resolving it.
Upvotes: 2
Views: 1067
Reputation: 780974
Add:
curl_setopt($ch, CURLOPT_POSTFIELDS, "{}");
so you send an empty JSON object as the parameter. This is the PHP equivalent of
-d "{}"
from the command line.
To put some other array into the post data, use json_encode
.
$data = array('userId' => array(),
'user_list' => array("1", "2", "3", "4", "5", "6", "7", "8")
);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data);
Upvotes: 1
Reputation: 29
You either need to set the method to 'GET' by removing curl_setopt($ch, CURLOPT_POST, true);
Or supplying valid JSON curl_setopt($curl, CURLOPT_POSTFIELDS, "{}");
Upvotes: 0