Search code examples
phpjsonapideezer

Deezer API and file_put_contents


I've got this script for saving albumart from Deezer to my server. The albumart url is alright, you can try yourself. And it does make a file but it's not the image I would like to see but a corrupted file. I am guessing it has something to do with the (I guess) 301 they provide when you visit the original link you get from the API. But I don't know hot to solve that problem if it is that.

<?php
// Deezer
$query = 'https://api.deezer.com/2.0/search?q=madonna';
$file = file_get_contents($query);
$parsedFile = json_decode($file);
$albumart = $parsedFile->data[0]->artist->picture;
$artist =  $parsedFile->data[0]->artist->name;

$dir = dirname(__FILE__).'/albumarts/'.$artist.'.jpg';
file_put_contents($dir, $albumart);
?>

Solution

  • Two issues:

    1) $albumart contains a URL (in your case http://api.deezer.com/2.0/artist/290/image). You need to do file_get_contents on that url.

    <?php 
    // Deezer 
    $query = 'https://api.deezer.com/2.0/search?q=madonna'; 
    $file = file_get_contents($query); 
    $parsedFile = json_decode($file); 
    $albumart = $parsedFile->data[0]->artist->picture; 
    $artist =  $parsedFile->data[0]->artist->name; 
    
    $dir = dirname(__FILE__).'/albumarts/'.$artist.'.jpg'; 
    file_put_contents($dir, file_get_contents($albumart));    // << Changed this line
    ?>
    

    2) The redirect may be a problem (as you suggest). To get around that, use curl functions.

    // Get file using curl.
    // NOTE: you can add other options, read the manual
    $ch = curl_init($albumart);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $data = curl_exec($ch);
    curl_close($ch);
    
    // Save output
    file_put_contents($dir, $data);
    

    Note, you should use curl() for handling getting content from external URLs as a matter of principal. Safer and you have better control. Some hosts also block accessing external URLS using file_get_contents anyway.