如何在if-else语句中获取PHP中的对象JSON?

发布于 2025-01-29 14:10:51 字数 311 浏览 0 评论 0原文

我想设置图像,但在第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'/>
);
?>

解决方案是什么?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

二货你真萌 2025-02-05 14:10:51

当API返回常规JSON时,您不需要foreach循环。也许您想获得这样的结果。

$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'/>";
 }

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'/>";
 }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文