質問編集履歴

2

コードを変更しました

2015/10/15 03:58

投稿

test_87097
test_87097

スコア45

test CHANGED
File without changes
test CHANGED
@@ -22,36 +22,78 @@
22
22
 
23
23
 
24
24
 
25
- public function extractionZip($data = null)
25
+ public function extractionZip($data = null, $destDir = TMP, $toEncoding = 'UTF-8')
26
26
 
27
27
  {
28
28
 
29
- $zipFile = TMP . 'zip/' . $data['Zip']['name'];
29
+ if (setlocale(LC_ALL, 'ja_JP.UTF-8') === false) {
30
30
 
31
- $zipFile = mb_convert_encoding($zipFile, 'UTF-8');
31
+ error_log('Locale not found: ja_JP.UTF-8');
32
+
33
+ exit();
34
+
35
+ }
32
36
 
33
37
  $zip = new ZipArchive;
34
38
 
39
+ $zipFile = TMP . 'zip/' . $data['Zip']['name'];
40
+
41
+ $hex = file_get_contents($zipFile, false, null, 7, 1);
42
+
43
+ $fromEncoding = (ord($hex) & 0x08) === 0x08 ? 'UTF-8' : 'CP932';
44
+
45
+ $sameEncoding = $fromEncoding === $toEncoding;
46
+
35
47
  $res = $zip->open($zipFile);
36
48
 
37
- if ($res === true){
49
+ if ($res === false){
38
50
 
39
- if (setlocale(LC_ALL, 'ja_JP.UTF-8') === false) {
51
+ return false;
40
52
 
41
- error_log('Locale not found: ja_JP.UTF-8');
42
-
43
- exit();
53
+ exit();
44
-
45
- }
46
-
47
- $dir = $zip->extractTo(TMP . 'zip');
48
-
49
- $zip->close();
50
-
51
- }else{
52
-
53
- echo 'error';
54
54
 
55
55
  }
56
56
 
57
+ $num_files = $zip->numFiles;
58
+
59
+
60
+
61
+ for ($i = 0; $i < $num_files; $i++) {
62
+
63
+ $stat = $zip->statIndex($i);
64
+
65
+ $name = $sameEncoding ? $stat['name']: mb_convert_encoding($stat['name'], $toEncoding, $fromEncoding);
66
+
67
+ if ($name[strlen($name)-1] === '/') {
68
+
69
+ continue;
70
+
71
+ }
72
+
73
+
74
+
75
+ $splited = explode('/', $name);
76
+
77
+ $baseName = array_pop($splited);
78
+
79
+ $dir = empty($splited) ? $destDir. implode('/', $splited). '/' : $destDir ;
80
+
81
+ if (is_dir($dir) === false) {
82
+
83
+ mkdir($dir, 0777, true);
84
+
85
+ }
86
+
87
+ file_put_contents("{$dir}{$baseName}", $zip->getFromIndex($i), LOCK_EX);
88
+
89
+ }
90
+
91
+ $dir = $zip->extractTo(TMP . 'zip');
92
+
93
+ $zip->close();
94
+
57
95
  }
96
+
97
+
98
+
99
+ ご回答を参考にして書いたコードです。解凍はするのですが、ディレクトリ名が日本語だと文字化けし、圧縮したファイル名が日本語だとそれも文字化けします。英語やlinuxで圧縮したファイルであれば問題ありません。

1

コードに少しミスがあったため

2015/10/15 03:58

投稿

test_87097
test_87097

スコア45

test CHANGED
File without changes
test CHANGED
@@ -32,6 +32,8 @@
32
32
 
33
33
  $zip = new ZipArchive;
34
34
 
35
+ $res = $zip->open($zipFile);
36
+
35
37
  if ($res === true){
36
38
 
37
39
  if (setlocale(LC_ALL, 'ja_JP.UTF-8') === false) {
@@ -42,7 +44,7 @@
42
44
 
43
45
  }
44
46
 
45
- $dir = $zip->extractTo(TMP . 'zip'), 'UTF-8';
47
+ $dir = $zip->extractTo(TMP . 'zip');
46
48
 
47
49
  $zip->close();
48
50