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!

LF00
  • 27,015
  • 29
  • 156
  • 295

2 Answers2

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!

chris85
  • 23,846
  • 7
  • 34
  • 51
kourouma_coder
  • 1,078
  • 2
  • 13
  • 24
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.

Cobra_Fast
  • 15,671
  • 8
  • 57
  • 102