I need to POST the following JSON code, but for some reason it is not working. Below is the code that I have.
$fieldString = "395609399";
//the curl request processor
function processCurlJsonrequest($URL, $fieldString) { //Initiate cURL request and send back the result
$ch = curl_init();
curl_setopt($ch, CURLOPT_HTTPHEADERS, array('Content-Type: application/json'));
curl_setopt($ch, CURLOPT_URL, $URL);
curl_setopt($ch, CURLOPT_USERAGENT, $this->_agent);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_COOKIEFILE, $this->_cookie_file_path);
curl_setopt($ch, CURLOPT_COOKIEJAR, $this->_cookie_file_path);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
curl_setopt($ch, CURLOPT_VERBOSE, TRUE);
if ($fieldCount) { // in case of post fields present then pass it on
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode("{categoryId: $fieldString}"));
curl_setopt($ch, CURLOPT_POST, 1);
}
$resulta = curl_exec($ch);
if (curl_errno($ch)) {
print curl_error($ch);
} else {
curl_close($ch);
}
return $resulta;
}
Here is the function which calls the cURL request:
function get_cat($categoryId, $URL) {
$fields = array(
"categoryId" => $categoryId
);
$fields_string = $fields;
return $this->processCurlJsonrequest($URL, $fields_string);
}
Send JSON data via POST with PHP cURLInitiate new cURL resource using curl_init(). Setup data in PHP array and encode into a JSON string using json_encode(). Attach JSON data to the POST fields using the CURLOPT_POSTFIELDS option. Set the Content-Type of request to application/json using the CURLOPT_HTTPHEADER option.
You can pass the body of the POST message to Curl with the -d or --data command-line option. Curl will send data to the server in the same format as the browser when submitting an HTML form. To send binary data in the body of a POST message with Curl, use the --data-binary command-line option.
To receive JSON string we can use the “php://input” along with the function file_get_contents() which helps us receive JSON data as a file and read it into a string. Later, we can use the json_decode() function to decode the JSON string.
It returns a pointer to an encoded string that can be passed as postdata. Using CURLOPT_POSTFIELDS implies setting CURLOPT_POST to 1. If CURLOPT_POSTFIELDS is explicitly set to NULL then libcurl will get the POST data from the read callback.
It's pretty simple really, make sure you've set the extra Content-Type header set for json, and then CURLOPT_POSTFIELDS can take the json as a string. No encoding necessary.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With