teratail header banner
teratail header banner
質問するログイン新規登録

回答編集履歴

1

回答追記

2017/01/05 07:22

投稿

Y.H.
Y.H.

スコア7918

answer CHANGED
@@ -15,4 +15,39 @@
15
15
 
16
16
  ```PHP
17
17
  @$zip->close();
18
+ ```
19
+ ----
20
+ 追記:
21
+ 何らかの処理中にzipに格納するファイルが確定しかつ複数あるのであれば、先にまとめて存在チェックを行ってから処理する方法もあります。
22
+
23
+ ```PHP
24
+ // 処理対象のファイル
25
+ $img_save_path = '/tmp/';
26
+ $targetfiles = array(
27
+ array('filename' => 'file01.txt', 'savename' => 'file01.txt'),
28
+ array('filename' => 'file02.txt', 'savename' => 'file02.txt'),
29
+ array('filename' => 'file03.txt', 'savename' => 'file03.txt')
30
+ );
31
+
32
+ // 処理対象のファイルの存在チェックを行い、存在するもののみのリストを作成
33
+ $existsfiles = array();
34
+ foreach($targetfiles as $targetfile){
35
+ if (file_exists($img_save_path.$targetfile['filename'])) {
36
+ $existsfiles[] = $targetfile;
37
+ } else {
38
+ echo 'file not found : ' . $img_save_path.$targetfile['filename'] . PHP_EOL;
39
+ }
40
+ }
41
+
42
+ // 存在するもののみのリストにしたがってzipを作成
43
+ if (count($existsfiles) > 0) {
44
+ $zip->open($zip_file, ZIPARCHIVE::CREATE | ZIPARCHIVE::OVERWRITE);
45
+ foreach($existsfiles as $targetfile){
46
+ $zip->addFile($img_save_path.$targetfile['filename'], $targetfile['savename']);
47
+ }
48
+ $zip->close();
49
+ } else {
50
+ echo 'did not create a zip file.' . PHP_EOL;
51
+ }
52
+
18
53
  ```