简体   繁体   English

PHP/Curl:如何显示来自外部 API 的图像?

[英]PHP/Curl: How do I display images from an external API?

I want to display images from the website "https://picsum.photos/v2/list", however when I try to echo out the url, I get a 404 error.我想显示来自网站“https://picsum.photos/v2/list”的图像,但是当我尝试回显 url 时,出现 404 错误。 What am I missing from my code?我的代码中缺少什么? This is what I have so far:这是我到目前为止所拥有的:

<?php
$url = "https://picsum.photos/v2/list";
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$picture = json_decode(curl_exec($curl), true);
curl_close($curl);
?>

<?php
  if(!empty($picture)){
    echo 'Picture:';
    foreach($picture as $post){
      echo '<img src= "'. $post["url"] .'" />';
    }
  }
?>

Your code is working fine in my PHP Server but you have one problem that you are using "url" element of array which is url for full page not for single image file.您的代码在我的 PHP 服务器中运行良好,但您有一个问题,即您使用数组的“url”元素,即 url 用于整页而不是单个图像文件。 But There is another element in your api response named "download_url" which return image, so if you change your code to below.但是在您的 api 响应中有另一个元素名为“download_url”,它返回图像,所以如果您将代码更改为下面。

<?php
$url = "https://picsum.photos/v2/list";
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$picture = json_decode(curl_exec($curl), true);
curl_close($curl);
?>

<?php
  if(!empty($picture)){
    echo 'Picture:';
    foreach($picture as $post){
      echo '<img src= "'. $post["download_url"] .'" />';
    }
  }
?>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM