Php Deezer API和文件内容
我有一个将albumart从Deezer保存到服务器的脚本。相册的网址是好的,你可以试试自己。它确实生成了一个文件,但它不是我想看到的图像,而是一个损坏的文件。我猜这与(我猜)当您访问从API获得的原始链接时他们提供的301有关。但如果是那样的话,我不知道该怎么解决这个问题Php Deezer API和文件内容,php,json,api,deezer,Php,Json,Api,Deezer,我有一个将albumart从Deezer保存到服务器的脚本。相册的网址是好的,你可以试试自己。它确实生成了一个文件,但它不是我想看到的图像,而是一个损坏的文件。我猜这与(我猜)当您访问从API获得的原始链接时他们提供的301有关。但如果是那样的话,我不知道该怎么解决这个问题 <?php // Deezer $query = 'https://api.deezer.com/2.0/search?q=madonna'; $file = file_get_contents($query); $p
<?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);
?>
两个问题:
1) $albumart
包含一个URL(在您的示例中)。您需要在该url上执行file\u获取内容
<?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
?>
注意,您应该使用curl()
处理从外部URL获取内容这一原则。更安全,你有更好的控制。某些主机还阻止使用文件获取内容访问外部URL。为什么不获取文件的标题(标题包含重定向)
我认为这是标题中的第四条记录,如果不使用print_r($hearderdata)检查它的话
这将返回图像文件的正确url
// 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);
$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);