我写了这段代码来从instagram下载图片。下载的图像,但它有一些错误。这意味着我可以下载图像,但我无法打开它
<?php
$linktopage = 'http://instagram.com/p/jTh1cBHG36/';
$sourcecode = file_get_contents( $linktopage );
$sourcecode = substr($sourcecode , strpos($sourcecode, 'og:image') + 19, strlen($sourcecode));
$sourcecode = substr($sourcecode , 0 , strpos($sourcecode, '"'));
$name= substr($sourcecode , strpos($sourcecode, 'com/') + 4, strlen($sourcecode));
$fileToSend = $sourcecode;
header('Content-type: image/jpeg');
header('Content-Disposition: attachment; filename='.$name.'"');
header("Content-Length: ". file_size($fileToSend));
readfile($fileToSend);
?>
答案 0 :(得分:0)
评论Content-Length
行,它会正常工作:
//header("Content-Length: ". file_size($fileToSend));
正确的函数名称为filesize
(我不确定它是否适用于您的网址)。
我也发现你在filename=
之后错过了一个引用。它应该是:
header('Content-Disposition: attachment; filename="'.$name.'"');
因此,您的代码的工作版本将是:
$linktopage = 'http://instagram.com/p/jTh1cBHG36/';
$sourcecode = file_get_contents( $linktopage );
$sourcecode = substr($sourcecode , strpos($sourcecode, 'og:image') + 19, strlen($sourcecode));
$sourcecode = substr($sourcecode , 0 , strpos($sourcecode, '"'));
$name= substr($sourcecode , strpos($sourcecode, 'com/') + 4, strlen($sourcecode));
$fileToSend = $sourcecode;
header('Content-type: image/jpeg');
header('Content-Disposition: attachment; filename="'.$name.'"');
//header("Content-Length: ". filesize($fileToSend));
readfile($fileToSend);
答案 1 :(得分:0)
由于拼写错误,问题正在发生。
错字错误发生在以下行:
header('Content-Disposition: attachment; filename='.$name.'"');
由于名称格式错误&#39; _&#39;被添加到文件扩展名。
代码中的另外一个内容是内容长度,仅为2行:
$head = array_change_key_case(get_headers($sourcecode, TRUE));
$filesize = $head['content-length'];
修正了拼写错误的最终工作代码:
<?php
$linktopage = 'http://instagram.com/p/jTh1cBHG36/';
$sourcecode = file_get_contents( $linktopage );
$sourcecode = substr($sourcecode , strpos($sourcecode, 'og:image') + 19, strlen($sourcecode));
$sourcecode = substr($sourcecode , 0 , strpos($sourcecode, '"'));
$name= substr($sourcecode , strpos($sourcecode, 'com/') + 4, strlen($sourcecode));
$fileToSend = $sourcecode;
$head = array_change_key_case(get_headers($sourcecode, TRUE));
$filesize = $head['content-length'];
header("Content-type: image/jpeg");
header("Content-Disposition: attachment; filename=".$name);
header("Content-Length: ". $filesize);
readfile($fileToSend);
?>