【问题标题】:PHP - How to save text file with ANSI encoding?PHP - 如何使用 ANSI 编码保存文本文件?
【发布时间】:2013-12-21 14:08:20
【问题描述】:

我在做:

file_put_contents("txt/myfile.txt", $fileContents);

我尝试了很多方法来强制我的文本文件为 ANSI,例如:

$fileContents = mb_convert_encoding($fileContents , mb_detect_encoding($fileContents , mb_detect_order(), true), 'WINDOWS-1252');

我也试过了:

$fileContents = iconv("ISO-8859-1", "WINDOWS-1252", $fileContents );

我需要 ANSI,因为当我使用 MS-DOS 中的“type”命令(Windows 7 中的 cmd.exe)打开文本文件时应该看起来不错

如果我打开当前文件,我可以看到 UTF-8 BOM:

C:\Users\XXX>输入 C:\myfile.txt

´╗┐V017666999 00000000000000005350005122013

如果我用 Notepad++ 打开文件并应用“转换为 ANSI”,我会得到(我需要的):

C:\Users\XXX>输入 C:\myfile.txt

V017666999 00000000000000005350005122013

有什么办法可以解决这个问题吗?提前致谢。

【问题讨论】:

标签: php utf-8 ansi plaintext


【解决方案1】:

如果您的 PHP 文件中有非 ASCII 字符,则需要首先转换 PHP 文件的编码。

如果您的非 ASCII 字符来自某些外部来源,则需要对其进行 iconv 处理。但不是来自 ISO-8859-1,而是来自外部源的编码。

【讨论】:

    【解决方案2】:

    现在我知道发生了什么,文件创建正确,但下载时添加了不需要的 BOM。

    这就是问题所在,我只需要改变这个:

    /* Bad code */
    header('Content-disposition: attachment; filename='.$_GET['filename']);
    header('Content-type: application/txt');
    readfile($_GET['filename']);
    

    至此(下载为二进制文件,使其保持不变):

    /* Good code */
    header('Content-disposition: attachment; filename='.$_GET['filename']);
    header('Content-type: application/txt');
    header('Content-Transfer-Encoding: binary');
    header('Content-Description: File Transfer');
    header('Content-Transfer-Encoding: binary');
    header('Cache-Control: must-revalidate');
    ob_clean();
    flush();
    readfile('txt/'.$_GET['filename']);
    

    (这最初是作为对问题的编辑发布的,但@Daniel 建议发布答案以进行澄清)。

    【讨论】:

      【解决方案3】:

      下面的正则表达式将去除各种 ansii 转义序列,包括颜色、ansii rgb colors、光标移动、换行,只保留 UTF-8 字符。

      控制台截屏示例:

      示例原始输入 作为图像,因为 html 页面没有显示转义码:

      使用 php 将 ANSII 颜色剥离为原始 UTF-8 文本:

      <?php    
      $ansii = " |[0m [34m▓▓▓▓▓[0m |[0m[2m.[0m[34m▓▓▓  [0m[2m.[0m|[0m [34m ▓▓▓ [0m |[0m[2m.[0m[34m▓ ▓ ▓[0m[2m.[0m|[0m [34m  ▓  [0m |[0m[2m.[0m[34m ▓▓▓ [0m[2m.[0m|[0m [34m▓▓▓  [0m |[0m[2m.[0m[34m▓▓▓▓▓[0m[2m.[0m| [2m[37m♞ [ENGINES] ♘♘♘♘♘♘♘♘♘♘♘♘♘♘ ♞[0m";
      
      echo preg_replace("/\x1B\[[0-9;]*[JKmsu]/","",$ansii);
      
      /* OUTPUT ----*/
      /* | ▓▓▓▓▓ |.▓▓▓  .|  ▓▓▓  |.▓ ▓ ▓.|   ▓   |. ▓▓▓ .| ▓▓▓   |.▓▓▓▓▓.| ♞ [ENGINES] ♘♘♘♘♘♘♘♘♘♘♘♘♘♘ ♞*/
      

      即使是 linux 命令行实用程序:iconv -f "ASCII" -t "UTF-8" 也无法解析 16bits rgb true colors ansii escape codes

      这可用于替换大多数 --不包括核心-- php-mbstring 包组件,因为例如 php strlen() 将返回正确的长度,就像 mb_strlen() .

      在线运行: https://3v4l.org/vRScD

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-02-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多