简体   繁体   中英

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. 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. But There is another element in your api response named "download_url" which return image, so if you change your code to below.

<?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"] .'" />';
    }
  }
?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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