【问题标题】:Creating zip file containing the files with UTF-8 encoding name in PHP using /usr/bin/zip使用 /usr/bin/zip 在 PHP 中创建包含具有 UTF-8 编码名称的文件的 zip 文件
【发布时间】:2015-01-04 02:15:52
【问题描述】:

我正在 PHP 中使用 /usr/bin/zip 创建和下载一个 zip 文件。问题是 zip 文件包含具有非 ASCII 文件名的 csv 文件。我下载了零字节文件,但该文件无效。

chdir($tmp_dir); // this is the directory where the files are written into

// CSV files that will be included in the zip file.
// assuming that the file already exist in $tmp_dir
$files = array();
$filename = "ショップ" . date("Ymd") . ".csv"; 
$fpath = $tmp_dir. DS . mb_convert_encoding($filename, "SJIS", "UTF-8");
$files[] = $fpath;

// The zip file to be created
$zip_file = "archive_" . date("Ymd").".zip";
$cmd = "/usr/bin/zip $zip_path *.csv";
exec($cmd);

// Force download
$fpath = $zip_file;
header("Content-Type: application/zip");
header('Content-Disposition: attachment; filename="' . $zip_path . '"');
header('Accept-Ranges: bytes');
if ($this->isIE()) {
  header("Cache-Control:private");
  header("Pragma:private"); 
}
header('Content-Length: ' . filesize($fpath));
readfile($fpath);

我试过ZipArchive,但同样的问题出现了。

chdir($tmp_dir); // this is the directory where the files are written into

// CSV files that will be included in the zip file.
// assuming that the file already exist in $tmp_dir
$files = array();
$filename = "ショップ" . date("Ymd") . ".csv";
$fpath = $tmp_dir. DS . mb_convert_encoding($filename, "SJIS", "UTF-8");
$files[] = $fpath; 

// The zip file to be created    
$zip_file = "archive_" . date("Ymd").".zip";    
$zip = new ZipArchive();
$zip->open($zip_path, ZipArchive::CREATE);
foreach ($files as $v) {
  $zip->addFile(basename($v));
}
$zip->close();

// Force download
$fpath = $zip_file;
header("Content-Type: application/zip");
header('Content-Disposition: attachment; filename="' . $zip_path . '"');
header('Accept-Ranges: bytes');
if ($this->isIE()) {
  header("Cache-Control:private");
  header("Pragma:private"); 
}
header('Content-Length: ' . filesize($fpath));
readfile($fpath);

有什么解决方法吗?当我从文件名中删除日文字符时,就可以了。

【问题讨论】:

    标签: php linux utf-8 zip non-ascii-characters


    【解决方案1】:

    我使用函数iconv 将文件名转换为正确的字符集解决了这个问题。

    $filename = iconv('SJIS', 'CP392//TRANSLIT', "ショップ" . date("Ymd") . ".csv");
    $fpath = $tmp_dir. DS . $filename;
    

    这意味着它将输入字符集SJIS 转换为文件名的输出字符集CP392。 CP392 是 code page 对应于 Shift JIS

    代码页 932(缩写为 CP932,也称为 IANA 名称 Windows-31J) 是微软对 Shift JIS 的扩展,包括 NEC 特殊字符(第 13 行),IBM 扩展的 NEC 选择(第 89 行) 至 92)和 IBM 扩展(第 115 至 119 行)。编码字符集 是 JIS X0201:1997、JIS X0208:1997 和这些扩展。 Windows-31J 经常被误认为是 Shift JIS:虽然相似,但区别是 对于希望避免使用 mojibake 的计算机程序员来说意义重大,并且 改用明确的 UTF-8 的好理由。 windows-31J 名称 但是是 IANA 的,并且不被微软认可,这在历史上 已改用 shift_jis。

    【讨论】:

      猜你喜欢
      • 2012-08-10
      • 1970-01-01
      • 2017-12-08
      • 2023-03-12
      • 1970-01-01
      • 2011-04-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多