1

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

6
  • Did you try to open this URL in browser's address bar? it doesn't open an image just a page with the image. I cannot be displayed as JPEG then Commented Feb 24, 2021 at 16:33
  • I don't see any errors, the code works ok for me. Check your web server logs, you might not have the curl module installed. Commented Feb 24, 2021 at 16:33
  • Network inspectors shows, that the URLs leads to text/html type of. How could he show the image then? Commented Feb 24, 2021 at 16:37
  • You'll want to switch url to download_url. Commented Feb 24, 2021 at 16:39
  • @El_Vanja Thanks so much, that worked for me! And thank you everyone else for your quick responses, I love this community :) <3 Commented Feb 24, 2021 at 16:42

1 Answer 1

1

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"] .'" />';
    }
  }
?>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.