php二进制流输出乱码的解决办法:1、打开本地“conn.php”和“print.php”文件;2、用“ob_clean”清空header内容,修改代码如“mysql_close();ob_clean();header("Content-type:$type");”。

本教程操作环境: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('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;
?>

这时候调用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('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;
?>


php 二进制流输出乱码怎么办