Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to declare variable from cURL PHP

I have an cURL file that will return an array like below and I wonder how can I declare the variable of [data]=>[id].I tried like $decoded.data or $decoded.[data] but it does not work.

Array
(
    [data] => Array
        (
            [id] => 2
            [email] => janet.weaver@reqres.in
            [first_name] => Janet
            [last_name] => Weaver
            [avatar] => https://reqres.in/img/faces/2-image.jpg
        )

    [support] => Array
        (
            [url] => https://reqres.in/#support-heading
            [text] => To keep ReqRes free, contributions towards server costs are appreciated!
        )

)

PHP file:

<?php
  $ch = curl_init();
  $url = "https://reqres.in/api/users/2";
  curl_setopt($ch,CURLOPT_URL,$url);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  $resp = curl_exec($ch);
  $decoded = json_decode($resp,true);
  print_r($decoded);
  curl_close($ch);
?>

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

$decoded['data']
$decoded['data']['id']

is the syntax. But the endpoint must return the array that you have printed with json_encode()

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading