-2

i want to setup image but got error in line 8

<?php
$url = "https://dog.ceo/api/breeds/image/random";
$json = file_get_content($url);
$obj = json_decode($json, TRUE);

foreach($obj as $key) if
(
echo <img src='$key['message']'/>

else

echo <img src='not_found.png'/>
);
?>

what's the solution?

  • What are you actually trying to test for with the `if`? It's not clear – ADyson May 15 '22 at 10:46
  • 1
    There are syntax errors galore here too...strings need quote marks round them being the most obvious. Make sure you understand such basics before you go too much further – ADyson May 15 '22 at 10:48
  • Use a decent IDE with PHP support that might hint on errors. Turn on error reporting/display ([How do I get PHP errors to display?](https://stackoverflow.com/questions/1053424/how-do-i-get-php-errors-to-display?rq=1)). Read the manual: [file_​get_​contents](https://www.php.net/manual/en/function.file-get-contents.php), [if](https://www.php.net/manual/en/control-structures.if.php), [echo](https://www.php.net/manual/en/function.echo.php) – brombeer May 15 '22 at 10:58
  • That API returns a pretty simple JSON, no need to `foreach` over it – brombeer May 15 '22 at 11:00
  • that is only example api i want to use on another api which is have many json – johan simanjuntak May 15 '22 at 13:07
  • Well you should give us an example of the one you actually want to target, not a different one...we are not mind-readers! – ADyson May 15 '22 at 13:46
  • im going to use for this [API](https://www.cpagrip.com/common/offer_feed_json.php?user_id=62608&pubkey=2e5325f825e6eea319fc99a30640fc58) maybe u can help im still confused while using foreach error – johan simanjuntak May 15 '22 at 16:06
  • Well, which data do you want to get from it? You should read https://stackoverflow.com/questions/29308898/how-to-extract-and-access-data-from-json-with-php to get the general idea and learn the concepts you need to get any such data – ADyson May 15 '22 at 17:14

1 Answers1

1

You don't need a foreach loop as the api returns regular json. Perhaps you wanted to get such a result.

$url = "https://dog.ceo/api/breeds/image/random";
$curl = curl_init();
curl_setopt_array($curl, array(
    CURLOPT_URL => 'https://dog.ceo/api/breeds/image/random',
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
    CURLOPT_CUSTOMREQUEST => 'GET',
));
$response = curl_exec($curl);
curl_close($curl);
$response = json_decode($response, TRUE); 
 if(!empty($response['message'])){
     echo "<img src='{$response['message']}'/>";
 }else{
     echo "<img src='not_found.png'/>";
 }
emrdev
  • 2,155
  • 3
  • 9
  • 15