1

I have recently started working with the PHP curl() function and I am trying to convert my retrieved JSON object to an associated array. Can anybody point me in the right direction? Thanks!

<?php
$ch = curl_init("https://canvas.instructure.com/api/v1/courses?access_token=7~8SXvaXHjMFZFHAdU5yU0pxNmVwAj40sjW7jRHw1Bvzq09QTFWrJRFxTu4pHAqSZU");
curl_exec($ch);
curl_close($ch);
?>

The response:

[{"account_id":81259,"course_code":"CS50","default_view":"feed","id":870674,"name":"CS50","start_at":"2014-08-05T18:29:18Z","end_at":null,"public_syllabus":false,"storage_quota_mb":250,"apply_assignment_group_weights":false,"calendar":{"ics":"https://canvas.instructure.com/feeds/calendars/course_6QRRvAKDngrrXtTBhzCA5Oz46g3aLgfRt7PNH0NN.ics"},"enrollments":[{"type":"student","role":"StudentEnrollment","enrollment_state":"active"}],"hide_final_grades":false,"workflow_state":"available"}]
1

1 Answer 1

1

Use CURLOPT_RETURNTRANSFER to capture the result in a string, which is what you pass to json_encode. I think you're passing $ch to json_decode which is not what you want. (As the error message states, $ch is a resource and json_decode expects to be passed a string).

$ch = curl_init("https://canvas.instructure.com/api/v1/courses?access_token=7~8SXvaXHjMFZFHAdU5yU0pxNmVwAj40sjW7jRHw1Bvzq09QTFWrJRFxTu4pHAqSZU");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// ...
$response = curl_exec($ch);

// $response will be false if the curl call failed
if($response) {
    var_dump(json_decode($response, true));
}

See curl_setopt documentation for more information.

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

2 Comments

Awesome! How come this doesn't print out though? if($response) { $array = var_dump(json_decode($response, true)); echo "@@@@@@@@@@@@@@"; echo $array[0]['account_id']; }
if you're assigning the return results of json_decode, remove the var_dump. I only put that in for illustration purposes.

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.