首页 > 解决方案 > 如何显示来自 JSON 文件 URL 的图像(本地主机存储)

问题描述

我正在尝试通过 JSON 文件让图像出现在我的网页上。我在下面的代码获取图像,并将其放在页面中,但这是我页面上显示的内容: 执行代码时的网页。因此,如果有人可以帮助我查明我的代码可能出错的地方,那就太好了。我不想直接使用图像文件,我需要让它通过 localhost。另外,是的,当我搜索图像 URL 时,照片确实出现了。

<?php
    
      $output = file_get_contents("ratings.json");
      
      $decode = json_decode($output, true);
    
      for($i = 0; $i < count($decode); $i++) {
    
      $imgUrl = $decode[$i]['image'];
    
    ?>
    
    <html>
      <body>
    
        <img src="<?php$imgUrl?>" height="70" width="70" class="img-thumbnail" /> <?php
        echo $imgUrl;
        }
        
        ?>
      </body>
    </html>

JSON文件:

[
    {
        "name": "Test",
        "review": "Test",
        "rating": "5",
        "image": "http:\/\/localhost\/ClassIA3\/images\/RobloxScreenShot20210104_132131740.png"
    },
    {
        "name": "The Storytellers",
        "review": "Test",
        "rating": "5",
        "image": "http:\/\/localhost\/ClassIA3\/images\/RobloxScreenShot20201012_195012147.png"
    },
    {
        "name": "ACTivate children's club for 3-4 years",
        "review": "Test",
        "rating": "4",
        "image": "http:\/\/localhost\/ClassIA3\/images\/RobloxScreenShot20210101_181318133.png"
    },
    {
        "name": "Flexibility and core training",
        "review": "Was so good for my core",
        "rating": "5",
        "image": "http:\/\/localhost\/ClassIA3\/images\/RobloxScreenShot20201120_213311711.png"
    },
    {
        "name": "The Letter 'B'",
        "review": "SO Cool",
        "rating": "1",
        "image": "http:\/\/localhost\/ClassIA3\/images\/untitled.png"
    }
]

标签: phpjson

解决方案


这里有几个问题。试试这个:

<html>
<body>
<?php
$output = file_get_contents("ratings.json");
$decode = json_decode($output, true);
for($i = 0; $i < count($decode); $i++) {
    $imgUrl = $decode[$i]['image'];
?>
<img src="<?php echo $imgUrl; ?>" height="70" width="70" class="img-thumbnail" /> <?php echo $imgUrl; ?>
<?php
}
?>
</body>
</html>

您不想在循环中开始您的 HTML 标记,它将为每个图像重复。此外,当您在 img 标签中设置 src 属性时,您需要回显 $imgUrl 变量。


推荐阅读