AnsweredAssumed Answered

cUrl value changes despite consistent arguments, ruins json_decode as a result? How to respond?

Question asked by Lee Newton on Jul 16, 2019
Latest reply on Jul 18, 2019 by Lee Newton

So a curl request I do seems to always return one of four different results.
Every time it has the same token, and the same header, and checks the same URL (https://my.test.instructure.com/api/v1/accounts/1/sis_imports.json?import_type=instructure_csv)
Then I initialise this curl request:

$ch = curl_init();
curl_setopt_array($ch, [
   CURLOPT_RETURNTRANSFER => true,

   CURLOPT_URL => $url,
   CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
   CURLOPT_SSL_VERIFYPEER => true,
   CURLOPT_HTTPHEADER => $headers,
   CURLOPT_VERBOSE => FALSE,
   CURLOPT_HEADER => TRUE,
]);
$resp = curl_exec($ch);
if (curl_exec($ch) == false) {
   echo 'Curl error: ' . curl_error($ch);
}
else {
   echo 'Operation complete without any errors. ';
}
$header_size = curl_getinfo( $ch, CURLINFO_HEADER_SIZE );
$header = substr( $resp, 0, $header_size );
$body = substr( $resp, $header_size );
dd($body);

When I dd($body), I find myself getting any one of four different results:

"""
"\r\n
\r\n
{"sis_imports":[{"id":1952,"created_at":"2019-07-12T14:55:27Z","started_at":"2019-07-12T15:00:55Z","ended_at":"2019-07-12T15:00:56Z","updated_at":"2019-07-12T15 ...
"""

---

"""
\n
\r\n
{"sis_imports":[{"id":1952,"created_at":"2019-07-12T14:55:27Z","started_at":"2019-07-12T15:00:55Z","ended_at":"2019-07-12T15:00:56Z","updated_at":"2019-07-12T15 ...
"""

---

"orts":[{"id":1952,"created_at":"2019-07-12T14:55:27Z","started_at":"2019-07-12T15:00:55Z","ended_at":"2019-07-12T15:00:56Z","updated_at":"2019-07-12T15:00:56Z", ..."

---

"{"sis_imports":[{"id":1952,"created_at":"2019-07-12T14:55:27Z","started_at":"2019-07-12T15:00:55Z","ended_at":"2019-07-12T15:00:56Z","updated_at":"2019-07-12T15 ..."

---

Why is this a problem? Because the very next line I want to do in my code is this:

$data = json_decode($body, true);

Depending on the value of $body, sometimes I get the sis_imports array that I need for my project, in which case everything is fine. But other times I get a null value and that terminates my program. Why can't it be consistent?

 

I need the material to be json-decodable or else my project won't work. And frankly, I don't understand why I am getting random values. I'm ok with either keeping my $body value constant, or adjusting what I do before json_decode().
What should I do? Any advice would be appreciated.

Outcomes