使用 PHP CURL 显示 PDF 文件只会产生奇怪的文本

Nic*_*mas 4 php curl pdf-generation

我正在使用 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;
Run Code Online (Sandbox Code Playgroud)

当我只是在浏览器中手动输入 URL 时,PDF 会正确显示。但是当使用 CURL 时,它会显示乱码文本页面。

在浏览器中查看代码视图,我看到很多这样的行:

5 0 obj
<</Length 6 0 R/Filter /FlateDecode>>
stream
Run Code Online (Sandbox Code Playgroud)

在 .pdf 应该显示的页面上,是以下代码:

<body>
    <p>
      <object id='mypdf' type='application/pdf' width='100%' height='90%' data='sample_report.pdf'>
      </object>
   </p>
</body>
Run Code Online (Sandbox Code Playgroud)

有没有人有什么建议?

thi*_*ish 7

试试这个(保持前 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;
Run Code Online (Sandbox Code Playgroud)

我注释掉的那行似乎没有做任何事情。我添加了“标题”行。如果我去掉那条线,我会像你一样得到一页胡言乱语。如果它仍然说“已发送标头”,则必须在其他地方设置标头。

编辑:

我还建议改变这一点:

<object id='mypdf' type='application/pdf' width='100%' height='90%' data='sample_report.pdf'></object>
Run Code Online (Sandbox Code Playgroud)

对此:

<iframe src="sample_report.pdf" width="100%" height="90%"></iframe>
Run Code Online (Sandbox Code Playgroud)

或者,如果您的 PHP 脚本名为 sample_report.pdf(例如),请尝试将 iframe src 更改为 sample_report.php。