2012-07-24 66 views
0

我已經有了這個腳本來保存從Deezer到我的服務器的albumart。 albumart的網址沒問題,你可以試試看。它確實創建了一個文件,但它不是我想看到的圖像,而是一個損壞的文件。我猜測它與你在訪問你從API獲得的原始鏈接時提供的(我猜)301有關。但如果是這樣的話,我不知道解決這個問題的熱點。Deezer API和file_put_contents

<?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); 
?> 

回答

0

兩個問題:

1)$albumart包含一個URL(你的情況http://api.deezer.com/2.0/artist/290/image)。您需要在該網址上執行file_get_contents

<?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)重定向可能是一個問題(如你所建議的)。爲了解決這個問題,使用捲曲函數。

// 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); 

注意,你應該使用curl()處理來自外部URL獲取的內容作爲主要的問題。更安全,你有更好的控制。無論如何,一些主機也會使用file_get_contents阻止訪問外部URL。

0

爲什麼不能獲取文件的標題(標題包含重定向)。

$headerdata=get_headers($albumart); 
echo($headerdata[4]);//show the redirect (for testing) 
$actualloc=str_replace("Location: ","",$headerdata[4]);//remove the 'location' header string 

file_put_contents($dir, $actualloc); 

我認爲這是頭中的第4條記錄,如果不是用print_r($ hearderdata)檢查它;

這將返回圖像文件的正確url。