Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/256.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php Deezer API和文件内容_Php_Json_Api_Deezer - Fatal编程技术网

Php Deezer API和文件内容

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

我有一个将albumart从Deezer保存到服务器的脚本。相册的网址是好的,你可以试试自己。它确实生成了一个文件,但它不是我想看到的图像,而是一个损坏的文件。我猜这与(我猜)当您访问从API获得的原始链接时他们提供的301有关。但如果是那样的话,我不知道该怎么解决这个问题

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