1

I'm running into an issue with formatting using the curl_setopt functions in PHP. I'm basically trying to re-create the cURL request below, but my code returns a bad request from the server. I'm pretty sure it has to do with poor formatting, but I can't figure out where I went wrong.

//This code returns the data back successfully
    curl -H "Content-Type: application/json" -d '{"bio_ids": ["1234567"]}' http://localhost:9292/program

    <?php //This code returns a bad request from the server
    $bio = array('bio_ids'=>'1234567');
    $curl = curl_init();
    curl_setopt_array($curl, array(
        CURLOPT_URL => 'http://localhost:9292/program',
        CURLOPT_POST => 1, // -d
        CURLOPT_POSTFIELDS => $bio,
        CURLOPT_HTTPHEADER => array('Content-Type: application/json'), // -H
    ));
    $resp = curl_exec($curl);
    curl_close($curl);

    ?>
3
  • 1
    In PHP, you're not sending JSON. You need a json_encode($bio). That might be all. Commented Jan 16, 2015 at 19:55
  • Oh interesting, I didn't realize it required the array in json object format. Perfect, thank you that solved my issue! Commented Jan 16, 2015 at 20:19
  • 1
    You're welcome. CURL wants a string of data. Only you know how to format your data into a string. Sometimes it's JSON, sometimes XML, sometimes http query string. Commented Jan 16, 2015 at 20:21

2 Answers 2

2

There are two issues:

You need to make sure that the structure of $bio matches what you are expected to pass, so the $bio declaration needs to be:

$bio = array('bio_ids' => array('1234567'));

Secondly you need to json_encode this data structure before sending it to the server:

CURLOPT_POSTFIELDS => json_encode($bio),
Sign up to request clarification or add additional context in comments.

Comments

1
<?php //This code returns a bad request from the server
    $bio = array('bio_ids'=>'1234567');
    $bio = json_encode($bio);
    $curl = curl_init();
    curl_setopt_array($curl, array(
        CURLOPT_URL => 'http://localhost:9292/program',
        CURLOPT_POST => 1, // -d
        CURLOPT_POSTFIELDS => $bio,
        CURLOPT_HTTPHEADER => array('Content-Type: application/json'), // -H
    ));
    $resp = curl_exec($curl);
    curl_close($curl);

    ?>

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.