Home >Backend Development >PHP Problem >How to deal with Chinese garbled characters in php zip

How to deal with Chinese garbled characters in php zip

藏色散人
藏色散人Original
2021-09-15 11:25:193007browse

php zip Chinese garbled solution: 1. Open the corresponding PHP code file; 2. Use PHP's zip encapsulation protocol to decompress to solve the ZipArchive garbled problem.

How to deal with Chinese garbled characters in php zip

The operating environment of this article: Windows 7 system, PHP 7.1 version, DELL G3 computer

What should I do if the Chinese php zip is garbled?

php decompression zip file garbled problem

Official operation method:

<?php
$zip = new \ZipArchive;
$zipfile = "./test.zip";
$res = $zip->open($zipfile);
$toDir = "./test";

$s = $zip->extractTo($toDir);
print_r(scandir($toDir));

Existing problems

If zip It is compressed on the Windows platform, so when the above code is executed on the Linux server, garbled characters will appear, and the decompressed files will also be missing.

Solution

Problem analysis:

ZipArchive garbled characters are caused by inconsistent encoding. The Windows file system is gbk encoded, while the file names in PHP ZipArchive are UTF-8 encoded. If the file name in the Zip archive contains special characters such as Chinese, it is inevitable to use PHP ZipArchive to decompress the garbled characters. The same reason applies when ZipArchive compressed files appear garbled or cannot be compressed.

Solution

Don’t use the built-in ZipArchive::extractTo() method to decompress ZipArchive documents, use PHP instead The zip packaging protocol is decompressed to solve the ZipArchive garbled code.

Solution code

<?php
$zip = new \ZipArchive;
$zipfile = "./test.zip";
$res = $zip->open($zipfile);

$toDir = "./test";
if(!file_exists($toDir)) {
   mkdir($toDir);
}
$docnum = $zip->numFiles;
for($i = 0; $i < $docnum; $i++) {
   $statInfo = $zip->statIndex($i);
   if($statInfo['crc'] == 0) {
       //新建目录
       mkdir($toDir.'/'.substr($statInfo['name'], 0,-1));
   } else {
       //拷贝文件
       copy('zip://'.$zipfile.'#'.$statInfo['name'], $toDir.'/'.$statInfo['name']);
   }
}

print_r(scandir($toDir));

Recommended learning: "PHP Video Tutorial"

The above is the detailed content of How to deal with Chinese garbled characters in php zip. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn