0

Deezerからサーバーにalbumartを保存するためのこのスクリプトがあります。albumartのURLは大丈夫です、あなたは自分で試すことができます。そして、それはファイルを作成しますが、それは私が見たい画像ではなく、破損したファイルです。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);
?>
4

2 に答える 2

0

2つの問題:

1)$albumartURLが含まれています(この場合はhttp://api.deezer.com/2.0/artist/290/image)。あなたはfile_get_contentsその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)リダイレクトが問題になる可能性があります(あなたが提案するように)。これを回避するには、curl関数を使用します。

// 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へのアクセスもブロックします。

于 2012-07-24T04:25:22.357 に答える
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);

print_r($ headerdata);でチェックしない場合は、ヘッダーの4番目のレコードだと思います。

これにより、画像ファイルの適切なURLが返されます。

于 2012-08-14T10:28:51.860 に答える