Different behaviour when using curl and file_get_contents

Hello

I am trying to access test data from the following free API site : http://dummy.restapiexample.com/api/v1/employees

I am trying to do this via the “curl” command but keep getting the error “Trying to get property ‘employee_name’ of non-object”

When I use the “file_get_contents” method though it works fine

Below is the 2 functions are am trying to use. “callapi” uses curl and does not work. “callapi2” uses the “get_file_contents” method and does work

What am I doing wrong with the curl command?

<?php

function callapi($url,$fieldname) {
   $ch = curl_init();
   
   curl_setopt($ch,CURLOPT_URL,$url);
   
   $result = curl_exec($ch);
   
   $data = json_decode($result);
   
   echo 'employee name : ' . $data[0]->{'employee_name'};
   
   curl_close($ch);
   
   return $data;

}

function callapi2($url,$fieldname) {

   
   $contdata = file_get_contents($url);
   
   echo $contdata;
   
   $jsonobj = json_decode($contdata);
   
   echo 'employee name : ' . $jsonobj[0]->{'employee_name'};
   
   return $jsonobj;

}


?>

Thanks
Mark

This error is unrelated to any API call in the first place. You have to check each variable up to where the data is missing.

    var_dump($data[0]);
    var_dump($data);
    var_dump($result);

as you see, nothing is returned, but there’s a flag for CURL you have to set…

Hi @mbeylis and a warm welcome to the forum.

I tried this LINK and the data downloaded OK

If you go to the homepage the Curl source script is supplied.

PS: just have a look at the manual:

https://www.php.net/manual/en/function.curl-exec.php

Hello

Thanks for the hint

I think you might have been referring to this :

curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

Set Return Transfer to True so as to return the values as a string rather than just output and all is working fine now

Thanks

Thanks for the info on the homepage. That was really helpful and pointed me in the right direction

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.