I want to access an API-link (JSON) but my PHP script strangely does not seem to find the correct values. It returns a NULL instead.
It cannot find $obj['message']['total-results'] even though I'm sure it exists (and when I open the API-Link manually in the browser, I do see it).
With the following code, therefore ...
<?php
# display errors
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
# curl function
# found via https://stackoverflow.com/questions/8540800/how-to-use-curl-instead-of-file-get-contents
function file_get_contents_curl($url) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_AUTOREFERER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
$apiurl = "https://api.crossref.org/journals/1389-5575/works?query=since-pub-date:2019-09-22&select=is-referenced-by-count"
# get JSON contents
$obj = file_get_contents_curl($apiurl);
$obj = json_decode($obj, true);
# handle error
if($obj == "Resource not found.") {
echo 'API connection failed';
} else {
echo 'API connection succeeded';
var_dump($obj); # NULL
if(!isset($obj['message']['total-results'])) {
echo '<br />ERROR: No $obj-message-total-results found!';
}
}
$new = $obj['message']['total-results']; // Warning: Trying to access array offset on value of type null ...
?>
... I get:
- "API connection succeeded"
- "ERROR: No $obj-message-total-results found!"
- "Warning: Trying to access array offset on value of type null"
Did I get anything wrong? I've been using that API for many years without any problems, so I'm really unsure what's the matter here. Thanks for your help!