0

It prints on the screen when it is correctly entered, but I do not want to do anything when it is entered incorrectly

How can I do that?

<?php
header('Content-type: text/html; charset=utf8');

$api_key = 'local';
$keyword = 'test';

$url = 'test.json' . $api_key . '&' .'keyword' .'=' . $GLOBALS['q'] ;

$open = file_get_contents($url);
$data = json_decode($open, true);

$istatistikler = $data['data'];
if ($data) {
foreach ( $istatistikler as $istatistik ){

    echo '<div class="right">';
    echo 'Oyun modu: ' . $istatistik['title'] . '<br />' .
    'Kazanma: ' . $istatistik['content'] . '<br />' .
    'Kazanma: ' . $istatistik['image'] . '<br />' .
    'Kazanma: ' . $istatistik['category'] . '<br />' .
    '<br />' .
    '<hr/>';
 $karakter_simge = 'http://google.com' . $istatistik['image'] . '';
 echo "<img src=".$karakter_simge." >" ;
 echo '</div>';
 }
  }
?>

Successful output

Failed output

Warning: file_get_contents(http://localhost/api/detail?X-Api-Key=local&keyword=a): failed to open stream: HTTP request failed! HTTP/1.1 406 Not Acceptable in /opt/lampp/htdocs/weather-master/php/php-api.php on line 10

"I do not want to print unsuccessfully"

thank you for your help!

3
  • Yep, I do not want to see Commented Jun 17, 2017 at 23:37
  • You should do that at your PHP configuration level. Disable the error displaying, that is best practice. You should check your logs for errors. Commented Jun 17, 2017 at 23:38
  • Thank you so much for your reply! Commented Jun 18, 2017 at 0:01

2 Answers 2

1

This may be helpful:

$open = @file_get_contents($url);

@ sign before a function name (in a call) prevents from showing any warnings (It's a bad practice though).

Good luck!

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much for your reply!
0

Change

$open = file_get_contents($url);

into

$open = @file_get_contents($url);
if ($open === false)
    die("wrong");

The @ suppresses the error message. Using die() will abort the script completely with the given message.

Alternatively, change the condition to !== false and wrap the rest of your "successful" code in its body:

$open = @file_get_contents($url);
if ($open !== false)
{
    $data = json_decode...
    ...
    ...
}

I guess I overshot the goal here a little, but not even running into code that won't work properly without its data isn't a bad idea at all.

1 Comment

Thank you so much for your reply, Problem solved!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.