0

I'm POSTing to an API that expects a json array called "updateRecord" in the body. I've tried a hundred different methods of getting the data across, but each method fails except for me literally writing the array as escaped text inside the CURLOPT_POSTFIELDS option.

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, "http://url.com/update");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, "{\"updateRecord\":[{\"fielda\":\"77777\",
\"fieldb\":\"11.77\",\"fieldc\":\"12\",\"fieldd\":\"12\",\"fielde\":\"99\",
\"fieldf\":\"01\",\"fieldg\":\"TEST\",
\"fieldh\":\"Y\",\"fieldi\":\"Approved\"}]}");
curl_setopt($ch, CURLOPT_POST, 1);

$headers = array();
$headers[] = "Authorization: Basic XXXXXXXXXXXXXXXXXX";
$headers[] = "Cache-Control: no-cache";
$headers[] = "Content-Type: application/json";
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$result = curl_exec($ch);
curl_close ($ch);

echo $result;

For static test data to prove the API works, this is fine, but I am lost on how to take a pre-existing array in PHP and convert it into a format that will work here, like:

curl_setopt($ch, CURLOPT_POSTFIELDS, $arr);

2
  • you've tried json_encode() ? curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($arr)); Commented Mar 26, 2018 at 21:53
  • Yup. No luck :( Commented Mar 26, 2018 at 22:02

1 Answer 1

3

you could use json_encode() to serialize your array:

$arr = array('updateRecord' => array(
    array(
      'fielda' => '77777',
      'fieldb' => '11.77',
      'fieldc' => '12',
      'fieldd' => '12',
      'fielde' => '99',
      'fieldf' => '01',
      'fieldg' => 'TEST',
      'fieldh' => 'Y',
      'fieldi' => 'Approved',
    ),
  ),
);

$serial = json_encode($arr) ;
curl_setopt($ch, CURLOPT_POSTFIELDS, $serial);

$serial will look like :

{"updateRecord":[{"fielda":"77777","fieldb":"11.77","fieldc":"12","fieldd":"12","fielde":"99","fieldf":"01","fieldg":"TEST","fieldh":"Y","fieldi":"Approved"}]}
Sign up to request clarification or add additional context in comments.

3 Comments

Yeah - one would ASSUME this would work, but it fails. The API returns a custom message to me "METHOD NOT SUPPORTED", which I believe indicates the syntax is not correct.... I may just have to keep it in this ugly format.
@BrianPowell The serialized string is equal to your example. The escape character \ comes from the fact that you use " inside a double quoted string. I've compared the two string (yours and the generated by json_encode()): they are the same.
Yes - I went over it again and I had a typo. Your solution works. Thank you!

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.