44
46

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

サブフォルダ内のファイルをまとめて取得する

Last updated at Posted at 2014-07-14

#まえがき
ファイル一覧をサブフォルダ内からもまとめて取得するサンプルメモ。

RecursiveIteratorIterator
RecusiveDirectoryIterator
を使えば自前で再帰処理作らないでいいから楽

#サンプル

ファイルのみ取得

main.php
<?php
$serch_dir = dirname(__FILE__) .'/files';

$files = new RecursiveIteratorIterator(
			new RecursiveDirectoryIterator($serch_dir,
					FilesystemIterator::CURRENT_AS_FILEINFO |
					FilesystemIterator::KEY_AS_PATHNAME |
					FilesystemIterator::SKIP_DOTS
			)
		);

foreach($files as $file_path => $file_info) {
	if (!$file_info->isFile()) {
		continue;
	}
	echo 'file path : '. $file_path                    .PHP_EOL;
	echo 'file size : '. $file_info->getSize()         .PHP_EOL;
	echo 'contents  : '. file_get_contents($file_path) .PHP_EOL;

	echo PHP_EOL;
}

フォルダも取得する

main.php
<?php
$serch_dir = dirname(__FILE__) .'/files';

$files = new RecursiveIteratorIterator(
			new RecursiveDirectoryIterator($serch_dir,
				FilesystemIterator::CURRENT_AS_FILEINFO |
				FilesystemIterator::KEY_AS_PATHNAME |
				FilesystemIterator::SKIP_DOTS
			),
			RecursiveIteratorIterator::SELF_FIRST
		);

foreach($files as $path => $info) {
	echo 'file path : '. $path              .PHP_EOL;
	echo 'file size : '. $info->getSize()   .PHP_EOL;

	if ($info->isFile()) {
		echo 'contents  : '. file_get_contents($path) .PHP_EOL;
	} else {
		echo 'contents  : not file!' .PHP_EOL;
	}

	echo PHP_EOL;
}

ファイル名でフィルター

main.php
<?php
$serch_dir = dirname(__FILE__) .'/files';

$files = new RecursiveIteratorIterator(
            new RecursiveDirectoryIterator($serch_dir,
                    FilesystemIterator::CURRENT_AS_FILEINFO |
                    FilesystemIterator::KEY_AS_PATHNAME |
                    FilesystemIterator::SKIP_DOTS
            )
        );

// 拡張子がtxtのファイルのみ抽出
$files = new RegexIterator($files, '/^.+\.txt$/i', RecursiveRegexIterator::MATCH);

foreach($files as $file_path => $file_info) {
	echo 'file path : '. $file_path                    .PHP_EOL;
	echo 'file size : '. $file_info->getSize()         .PHP_EOL;
	echo 'contents  : '. file_get_contents($file_path) .PHP_EOL;

	echo PHP_EOL;
}
44
46
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
44
46

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?