我使用PHP CURL访问PDF文件,除了最终结果不可读之外,一切都正常工作。我的代码如下:
$cookie = 'cookies.txt';
$timeout = 30;
$url = "http://www.somesite.com/sample_report.pdf";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout );
curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie);
curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Encoding: none','Content-Type: application/pdf'));
$result = curl_exec($ch);
echo $result;
当我只是在浏览器中手动输入URL时,PDF会正确显示。但当使用CURL时,它会显示一页页胡言乱语的文本。
在浏览器中查看代码视图时,我看到了很多这样的行:
5 0 obj
<</Length 6 0 R/Filter /FlateDecode>>
stream
pdf应该显示的页面上有以下代码:
<body>
<p>
<object id='mypdf' type='application/pdf' width='100%' height='90%' data='sample_report.pdf'>
</object>
</p>
</body>
有人有什么建议吗?
试试这个(保持前3行不变)
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout );
curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie);
curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie);
//curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Encoding: none','Content-Type: application/pdf'));
header('Content-type: application/pdf');
$result = curl_exec($ch);
curl_close($ch);
echo $result;
我评论的那句话似乎没有任何作用。我添加了"标题"行。如果我把那一行去掉,我会像你一样收到一页胡言乱语。如果它仍然写着"页眉已经发送",那么肯定有什么东西在其他地方设置了页眉。
编辑:
我还建议改变这个:
<object id='mypdf' type='application/pdf' width='100%' height='90%' data='sample_report.pdf'></object>
对此:
<iframe src="sample_report.pdf" width="100%" height="90%"></iframe>
或者,如果您的PHP脚本名为sample_report.pdf(例如),请尝试将iframe-src更改为sample_report.PHP。