php 二進位流輸出亂碼怎麼辦

藏色散人
發布: 2023-03-17 07:50:01
原創
1928 人瀏覽過

php二元流輸出亂碼的解決方法:1、開啟本機「conn.php」和「print.php」檔案;2、用「ob_clean」清空header內容,修改程式碼如「mysql_close(); ob_clean();header("Content-type:$type");」。

php 二進位流輸出亂碼怎麼辦

本教學操作環境:windows7系統、PHP8.1版、Dell G3電腦。

php 二進位流輸出亂碼怎麼辦?

最近在用php開發從mysql讀取並輸出二進位文件,遇到了亂碼問題。

一般輸出二進位檔案是用下面的方法:

<?php
if(!isset($id) or $id=="") die("error: id none");
//定位记录,读出
$conn=mysql_connect("127.0.0.1","***","***");
if(!$conn) die("error : mysql connect failed");
mysql_select_db("test",$conn);
$sql = "select * from receive where id=$id";
$result = mysql_query($sql);
$num=mysql_num_rows($result);
if($num<1) die("error: no this recorder");
$data = mysql_result($result,0,"file_data");
$type = mysql_result($result,0,"file_type");
$name = mysql_result($result,0,"file_name");
mysql_close($conn);
//先输出相应的文件头,并且恢复原来的文件名
header("Content-type:$type");
header("Content-Disposition: attachment; filename=$name");
echo $data;
?>
登入後複製

用上面的方法是沒有問題的。但如果把database 連線封裝在一個單獨的檔案中,就有問題了。改寫上面的程式碼為2個檔案:

//conn.php
<?php
function Open_DB(){
$conn=mysql_connect("127.0.0.1","***","***");
if(!$conn) die("error : mysql connect failed");
mysql_select_db("test",$conn);
}
?>
登入後複製
//print.php
<?php
if(!isset($id) or $id=="") die("error: id none");
//定位记录,读出
require_once(&#39;conn.php&#39;);
Open_DB();
$sql = "select * from receive where id=$id";
$result = mysql_query($sql);
$num=mysql_num_rows($result);
if($num<1) die("error: no this recorder");
$data = mysql_result($result,0,"file_data");
$type = mysql_result($result,0,"file_type");
$name = mysql_result($result,0,"file_name");
mysql_close();
header("Content-type:$type");
header("Content-Disposition: attachment; filename=$name");
echo $data;
?>
登入後複製

這時候呼叫print.php開啟word檔案時會產生亂碼。問題就出在"require_once('conn.php')"語句。 php在呼叫該語句時會在header中輸出,這影響到了後面的2個header語句,從而破壞了word檔案的資料流。因此打開的word檔案會是亂碼。

解決的方法是用ob_clean清空header內容。改寫的print.php 如下

//print.php
<?php
if(!isset($id) or $id=="") die("error: id none");
//定位记录,读出
require_once(&#39;conn.php&#39;);
Open_DB();
$sql = "select * from receive where id=$id";
$result = mysql_query($sql);
$num=mysql_num_rows($result);
if($num<1) die("error: no this recorder");
$data = mysql_result($result,0,"file_data");
$type = mysql_result($result,0,"file_type");
$name = mysql_result($result,0,"file_name");
mysql_close();
ob_clean();
header("Content-type:$type");
header("Content-Disposition: attachment; filename=$name");
echo $data;
?>
登入後複製

推薦學習:《PHP影片教學

以上是php 二進位流輸出亂碼怎麼辦的詳細內容。更多資訊請關注PHP中文網其他相關文章!

相關標籤:
來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!