0

I am new to PHP and have been trying to access to the API for the past 2 hours. Everytime i request for the json object, it kept giving me null. I am sure i filled up the URL and Accountkey correctly. Can comeone please correct me if i did anything wrong with the code below. Thank you.

<?php
   $ch = curl_init();
   curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
   curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
   curl_setopt($ch, CURLOPT_URL, 'http://urlxxxxxxxx.com');

   $header = array(
   'AccountKey:' => 'xxxx',
   'Accept:' => 'application/json');

   curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
   $result = curl_exec($ch);
   $obj = json_decode($result);
   curl_close($ch);

   print "<pre>";
   print_r($obj);
   print "</pre>";
?>
  • Do you confirm `$result` is a valid json string? If it is `false`, check what `curl_error($ch)` returns. – Alex Blex Sep 21 '17 at 15:14
  • Possible duplicate of [PHP cURL custom headers](https://stackoverflow.com/questions/8115683/php-curl-custom-headers) – ponury-kostek Sep 21 '17 at 15:17
  • @ZhenHui any output after fixing `key=>value` pattern to `key:value` ? – A l w a y s S u n n y Sep 21 '17 at 15:25
  • yes the output is what i got back from the API which is the data i need. Format is in json type –  Sep 21 '17 at 15:46
  • 1
    "json type" is not necessarily a valid parsable json. `json_decode` returns false when it fails to parse the string. Check what [json-last-error](http://php.net/manual/en/function.json-last-error.php) returns, or try to check the result in a json validator online. – Alex Blex Sep 21 '17 at 16:11

1 Answers1

0

Try to set CURL http headers like this, not as php array key=>value pattern.

 $header = array(
   'AccountKey: xxxx',
   'Accept:application/json'
 );
A l w a y s S u n n y
  • 36,497
  • 8
  • 60
  • 103