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?
CodePudding user response:
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'/>";
}