4

I need to make a POST request to an external http API using curl. When I call the API using the curl command line, it returns the correct data. However, I'm struggling to get the right data when calling it from a php script.

When I use the curl command from the terminal, I get the correct data:

curl -i -H "Accept: application/json" -X POST -d "type_category_id=4" http://example.com/api/

What is the correct format for the CURLOPT_POSTFIELDS in my curl_setopts() in php?

I tried the following (and failed):

<?php
$data = "type_category_id=4";

$ch = curl_init('http://example.com/api/');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    'Content-Type: application/json',
    'Content-Length: ' . strlen($data))
);

$result = curl_exec($ch);
?>
3
  • show us your php script Commented Dec 2, 2013 at 1:27
  • I've edited the question with the code. Commented Dec 2, 2013 at 1:33
  • 3
    curl_setopt($ch, CURLOPT_POST, 1); and drop the CURLOPT_CUSTOMREQUEST Commented Dec 2, 2013 at 1:39

1 Answer 1

6

Make it Accept: application/json instead of Content-Type: application/json

You have done that in the command line but not in the php script.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.