2012-07-24 69 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。