0

I am trying to learn to retrieve data from APIs. I am accessing an API that requires POST and I am therefore using cURL:

$curl = curl_init();

curl_setopt_array($curl, array(
  CURLOPT_URL => "api-url-here",
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => "",
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 30,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => "POST",
  CURLOPT_POSTFIELDS => "api_key=myapikey&format=json&logs=1&search=mykeyword", "method=JSON",
  CURLOPT_HTTPHEADER => array(
    "cache-control: no-cache",
    "content-type: application/x-www-form-urlencoded"
  ),
));

$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);

So far so good.

If I echo the $response I get the JSON result for the keyword I am searching. But how to I get a single element from them result?

I try to use json_decode($response), but I get this error:

Catchable fatal error: Object of class stdClass could not be converted to string
Apo
  • 157
  • 3
  • 17
  • 1
    please share `$response` text you are receiving from the API – Abhishek Jun 13 '18 at 06:14
  • {"stat":"ok","pagination":{"offset":0,"limit":50,"total":1},"monitors":[{"id":780536830,"friendly_name":"Bangkokguide","url":"http://bangkokguide.dk/","type":2,"sub_type":"","keyword_type":2,"keyword_value":"Alt om Bangkok","http_username":"","http_password":"","port":"","interval":1800,"status":2,"ssl":{"brand":"","product":null,"expires":0},"create_datetime":1528321171,"logs":[{"type":2,"datetime":1528317598,"duration":552970,"reason":{"code":"999999","detail":"Keyword Found"}},{"type":98,"datetime":1528317561,"duration":37,"reason":{"code":"98","detail":"Monitor started"}}]}]} – digitalmads Jun 13 '18 at 06:17
  • use `json_decode($response,true)`. While printing that don't use `echo` use `var_dump` or `var_export` – Abhishek Jun 13 '18 at 06:19
  • This is just a suggestion out of the context of what you have asked. You can try [Guzzle](http://docs.guzzlephp.org/en/stable/) for API Calls. – Abhishek Jun 13 '18 at 06:23

1 Answers1

1

I think you can try using this

$decoded=json_decode($response, true);

instead of this

$decoded = json_decode($response);

It will convert your stdClass to array. Note that $decoded is array then you can use as you require.

Use var_dump($decoded) to debug the object

munsifali
  • 1,732
  • 2
  • 24
  • 43