iT邦幫忙

0

如何讓 download 下來的文字檔之編碼,變成 ANSI ?

  • 分享至 

  • xImage

我是用下列方式,download 文字檔下來,但它都會變成 utf-8 ,可是我需要的是 ANSI ,我應該如何修改程式碼?

<?php
	$myFile = '/tmp/123.txt'
	header("Cache-Control: public, must-revalidate");
	header("Pragma: hack");
	header("Content-Type: application/text");
	header("Content-Length: " .(string)(filesize($myFile)) );
	header('Content-Disposition: attachment; filename="'.$filename.'"');
	header("Content-Transfer-Encoding: binary\n");
	readfile($myFile);
?>
淺水員 iT邦大師 6 級 ‧ 2023-06-10 01:39:20 檢舉
原本的 /tmp/123.txt 是什麼編碼?
ckp6250 iT邦好手 1 級 ‧ 2023-06-10 04:28:46 檢舉
utf-8
ckp6250 iT邦好手 1 級 ‧ 2023-06-10 11:38:36 檢舉
已經解決了,採用下列方式

https://www.twblogs.net/a/5ee6cc61e61d3441c68b2d15
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

2 個回答

1
淺水員
iT邦大師 6 級 ‧ 2023-06-10 14:51:58
最佳解答

我覺得要注意一下,ANSI 的說法並不明確,不同的地區實際上是不同的編碼
在繁體中文系統,是指 Big5
簡體中文系統,是指 GB2312
對日本人來說,是指 Shift-JIS
不同國家會有不同的編碼,可以參考:頁碼

所以只說 ANSI 而不說地區,也沒有給原始檔案內容
沒人猜得到要轉成哪個地區的編碼

已經解決了,採用下列方式 https://www.twblogs.net/a/5ee6cc61e61d3441c68b2d15

那個連結中,提到 unicode 是 2 byte 是錯誤的
unicode 只定義字與 unicode 數值的對應關係
而實際編碼是透過 utf-8、utf-16、utf-32、UCS-2 ... 來表達

淺水員 iT邦大師 6 級 ‧ 2023-06-10 15:50:45 檢舉

關於 ANSI,舉個範例好了
如果在繁體中文環境,文字檔只有「屣」一個字
(位元組資料為:E1A2)
那麼在簡體中文環境會看到「幄」
日文環境會看到「發」

下面是模擬的程式

let binaryString = new Uint8Array([0xe1, 0xa2]);
console.log(new TextDecoder('big5').decode(binaryString));
console.log(new TextDecoder('shift-jis').decode(binaryString));
console.log(new TextDecoder('gb2312').decode(binaryString));
ckp6250 iT邦好手 1 級 ‧ 2023-06-10 21:01:09 檢舉

感謝指導。
我這個檔案,是要給銀行轉發薪水的,因為接手的舊程式(vfp 寫的),它產出的檔案是 ansi (繁體中文),但我PHP產出的是 utf-8 , 我希望和舊檔案一模一樣,才會需要轉成 ansi , 本來也以為很簡單,實作之後,才發現不容易,最後是這個程式解決了問題。

0
rogeryao
iT邦超人 8 級 ‧ 2023-06-09 17:45:12
ckp6250 iT邦好手 1 級 ‧ 2023-06-10 04:29:42 檢舉

十分感恩,
但我試了無效。

我要發表回答

立即登入回答