簡體   English   中英

使用PHP CURL顯示PDF文件只會產生奇怪的文本

[英]Using PHP CURL to display PDF file is just producing strange text

我正在使用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>

有沒有人有什么建議?

嘗試一下(保持前三行相同)

$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。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM