PHP從mysql中讀取並輸出二進位制檔案的亂碼問題

2021-05-23 10:09:23 字數 2496 閱讀 3367

最近在用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()

?>

//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;

?>

C 從資料庫讀取資料並輸出

連線資料庫,並從資料庫中讀取資料後並輸出 using system using system.collections.generic using system.linq using system.text using system.data.sqlclient namespace login nam...

PHP使用PDO從mysql讀取大量資料處理詳解

前言 環境適用場景 需要處理一定資料集業務 pdo 關鍵設定 dbh new pdo dsn,user,pass 關鍵設定,如果不設定,php依舊會從pdo一次取出資料到php dbh setattribute pdo mysql attr use buffered query,false perp...

python 讀取excel內容並輸出

讀取excel內容並用print輸出。import pandas as pd df pd.read excel 測試.xlsx 這個會直接預設讀取到這個excel的第乙個表單 data df.head 預設讀取前5行的資料 print 獲取到所有的值 n format data 格式化輸出 方法二 ...