溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

php二進制流輸出亂碼如何解決

發(fā)布時間:2022-10-24 16:28:05 來源:億速云 閱讀:162 作者:iii 欄目:編程語言

這篇文章主要介紹了php二進制流輸出亂碼如何解決的相關(guān)知識,內(nèi)容詳細易懂,操作簡單快捷,具有一定借鑒價值,相信大家閱讀完這篇php二進制流輸出亂碼如何解決文章都會有所收獲,下面我們一起來看看吧。

php二進制流輸出亂碼的解決辦法:1、打開本地“conn.php”和“print.php”文件;2、用“ob_clean”清空header內(nèi)容,修改代碼如“mysql_close();ob_clean();header("Content-type:$type");”。

php 二進制流輸出亂碼怎么辦?

最近在用php開發(fā)從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('conn.php');
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;
?>

這時候調(diào)用print.php打開word文件時會產(chǎn)生亂碼。問題就出在"require_once('conn.php')"語句。php在調(diào)用該語句時會在header中輸出,這影響到了后面的2個header語句,從而破壞了word文件的數(shù)據(jù)流。因此打開的word文件會是亂碼。

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

//print.php
<?php
if(!isset($id) or $id=="") die("error: id none");
//定位記錄,讀出
require_once('conn.php');
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;
?>

關(guān)于“php二進制流輸出亂碼如何解決”這篇文章的內(nèi)容就介紹到這里,感謝各位的閱讀!相信大家對“php二進制流輸出亂碼如何解決”知識都有一定的了解,大家如果還想學習更多知識,歡迎關(guān)注億速云行業(yè)資訊頻道。

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

php
AI