1

I have the following request to an API:

$url = "{{correctURLishere}}";
$response = json_decode(file_get_contents($url), true);
$name =  $response["title"];
} 

The This should bring back the value from they key "title" in this json response. But instead, the error I get is

file_get_contents(url): failed to open stream: HTTP request failed! HTTP/1.1 402

I know the error is because I am only allowed 150 requests a day and have exceeded this amount but can someone help me to echo "No more requests allowed" instead of the error?

I have tried the following but it wont work:

if(json_decode(file_get_contents($url), true)) {
$response = json_decode(file_get_contents($url), true);
$name =  $response["title"];
}

Could anyone tell me how to help with the error? Thanks

Shauna
  • 181
  • 10
  • Are you though? [Are you really](https://www.php.net/manual/en/filesystem.configuration.php)? Because I don't see you mention (with proof, of course) that you already made sure to allow fopen to act on URLs. – Mike 'Pomax' Kamermans Mar 28 '20 at 23:57
  • Does this answer your question? [PHP file\_get\_contents() returns "failed to open stream: HTTP request failed!"](https://stackoverflow.com/questions/697472/php-file-get-contents-returns-failed-to-open-stream-http-request-failed) – A. Meshu Mar 29 '20 at 00:02
  • 1
    Does this answer your question? [How can I handle the warning of file\_get\_contents() function in PHP?](https://stackoverflow.com/questions/272361/how-can-i-handle-the-warning-of-file-get-contents-function-in-php) – El_Vanja Mar 29 '20 at 00:03

1 Answers1

-1

try to use try catch section, for example

try{
    if(json_decode(file_get_contents($url), true)) {
        $response = json_decode(file_get_contents($url), true);
        $name =  $response["title"];
    }
}catch(Exception $e){
    print_r($e);
    echo '<br>';
    echo $e->getMessage();
}

for your referrence: https://www.php.net/manual/en/language.exceptions.php

Josua Marcel C
  • 3,122
  • 6
  • 45
  • 87