php excel reader2.21匯出excel中文亂碼解決方案說明

來源:互聯網
上載者:User

  之前我的PHP教程部落格訪友詢問使用php excel reader2.21匯出excel時中文出現亂碼如何解決,現我說明下php excel reader匯出excel中文亂碼的解決方案,希望對使用php excel reader匯出excel的朋友有所協助。

  php excel reader介紹

  php excel reader是一個讀取Excel xsl檔案內容的一個php excel類,目前最新版本是php excel reader2.21,網上可自行搜尋,sourceforge上的php excel reader下載地址我估計是初始版,本教程所介紹的php excel reader匯出excel中文亂碼解決方案是基於php excel reader2.21,故不同版本php匯出excel亂碼的解決方案是有區別的,請務必下載正確的php excel reader版本。

  如何解決php excel reader2.21匯出excel中文亂碼?

  在下載完php excel reader2.21後,請解壓至你的PHP環境配置的運行目錄下,開啟example.php,首先來看

1
$data=new Spreadsheet_Excel_Reader("example.xls");

  此語句是用來建立一個php匯出excel的執行個體,在excel_reader2.php檔案中我們可以找到此php excel reader類的建構函式原型

1
Spreadsheet_Excel_Reader($file='',$store_extended_info=true,$outputEncoding='')

  顧名思義,php excel reader匯出excel檔案內容的編碼類別型是通過$outputEncoding參數來指定的,預設的php excel reader匯出excel的編碼類別型是通過變數_defaultEncoding設定,預設為UTF-8,所以通常解決php excel reader匯出excel中文亂碼有兩種方法。

  php excel reader匯出excel中文亂碼解決方案一

1
$data=new Spreadsheet_Excel_Reader("example.xls");

改為

1
$data=new Spreadsheet_Excel_Reader("example.xls",true,"GB2312");

  php excel reader匯出excel中文亂碼解決方案二:開啟excel_reader2.php,找到

1
var$_defaultEncoding="UTF-8";

修改為

1
var$_defaultEncoding="GB2312";

  即可解決php excel reader匯出excel亂碼的問題。

  那為什麼通過上述教程修改後,如果在example.xls中添加中文後example.php仍然輸出亂碼呢?這是因為其調用了php excel reader類中的dump函數,此函數是用來將匯出的excel檔案內容以HTML的形式輸出,而問題恰恰是由於這個函數中htmlentities函數作怪,htmlentities函數是用來把字元轉換為HTML實體的,原型如下

1
htmlentities(string,quotestyle,character-set)

  其預設的字元集為ISO-8859-1,所以當使用php excel reader的dump函數匯出excel出現中文亂碼時,

  解決方案一

1
$val=htmlentities($val);

修改為

1
$val=htmlentities($val,ENT_COMPAT,"GB2312");

  解決方案二

1
$val=htmlentities($val);

修改為

1
$val=htmlspecialchars($val);

  php excel reader匯出excel中文亂碼解決方案總結

  如果不使用dump函數匯出excel,可以通過修改_defaultEncoding變數或者通過new Spreadsheet_Excel_Reader(excel檔案名稱,true,”GB2312″);解決匯出excel亂碼問題,如果使用dump函數以HTML的方式匯出excel,需要修改htmlentities函數解決匯出excel亂碼問題。

  至此,使用php excel reader2.21匯出excel中文亂碼時如何解決就介紹完了。

  :PHP網站開發教程-leapsoul.cn著作權,轉載時請以連結形式註明原始出處及本聲明,謝謝。



聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.