lxkmxl
lxkmxl

Reputation: 81

Getting image data using the Imgur API and PHP

I'm quite new to php and I'm trying to use the imgur API (My code is based on several tutorials) What I'm trying to do is get an image from imgur display it on a web page. So I'm using this code

<?php  
  $client_id = '<ID>';

  $ch = curl_init();
  curl_setopt($ch,CURLOPT_URL,'https://api.imgur.com/3/image/rnXusiA');
  curl_setopt($ch,CURLOPT_CONNECTTIMEOUT, 5);
  curl_setopt($ch,CURLOPT_FOLLOWLOCATION, true);
  curl_setopt($ch,CURLOPT_RETURNTRANSFER, true);
  curl_setopt($ch, CURLOPT_HTTPHEADER, array('Authorization: Client-ID ' . $client_id));
  $result = curl_exec($ch);
  curl_close($ch);

  $json = json_decode($result, true);
?>

After converting $result to an associative array, I'm trying to access data

$data = $json->data->link;

But there's nothing in $data and I'm getting a Trying to get property of non-object error. I'm assuming imgur didn't return any data. So what am I doing wrong?

Upvotes: 4

Views: 1782

Answers (1)

lxkmxl
lxkmxl

Reputation: 81

I read more about curl and re-wrote the code.

<?php 
  $client_id = "<ID>";
  $c_url = curl_init();
  curl_setopt($c_url, CURLOPT_SSL_VERIFYPEER, false);
  curl_setopt($c_url, CURLOPT_RETURNTRANSFER, true);
  curl_setopt($c_url, CURLOPT_URL,"https://api.imgur.com/3/image/rnXusiA");
  curl_setopt($c_url, CURLOPT_HTTPHEADER, array('Authorization: Client-ID ' . $client_id));
  $result=curl_exec($c_url);
  curl_close($c_url);
  $json_array = json_decode($result, true);
  var_dump($json_array);
?>

This wokred and var_dump($json_array); displayed the array content.

$json_array['data']['link']; gives the direct link to the image.

For an album, I changed the URL to https://api.imgur.com/3/album/y1dZJ and used a loop to get the image links

$image_array = $json_array["data"]["images"];

foreach ($image_array as $key => $value) {
    echo $value["link"];
}

I hope this helps anyone who's new to the imgur API.

Upvotes: 1

Related Questions