Skip to content

Instantly share code, notes, and snippets.

@k-holy
Created February 16, 2012 09:34
Show Gist options
  • Save k-holy/1843634 to your computer and use it in GitHub Desktop.
Save k-holy/1843634 to your computer and use it in GitHub Desktop.
RecursiveIteratorIterator + RecursiveDirectoryIterator
<?php
namespace Acme;
$mode = \RecursiveIteratorIterator::LEAVES_ONLY;
//$mode = \RecursiveIteratorIterator::SELF_FIRST;
//$mode = \RecursiveIteratorIterator::CHILD_FIRST;
$iterator = new \RecursiveIteratorIterator(
new \RecursiveDirectoryIterator(__DIR__ . DIRECTORY_SEPARATOR . 'DIR',
\FilesystemIterator::CURRENT_AS_FILEINFO | // current()メソッドでSplFileInfoのインスタンスを返す
\FilesystemIterator::KEY_AS_PATHNAME | // key()メソッドでパスを返す
\FilesystemIterator::SKIP_DOTS // .(カレントディレクトリ)および..(親ディレクトリ)をスキップ
),
$mode
);
echo '<pre>';
foreach ($iterator as $key => $node) {
var_dump($node->getFilename());
}
echo '</pre>';
<?php
namespace Acme;
class ExcludeFileFilterIterator extends \FilterIterator
{
public function accept()
{
return $this->getInnerIterator()->current()->isDir();
}
}
$iterator = new \RecursiveIteratorIterator(
new \RecursiveDirectoryIterator(__DIR__ . DIRECTORY_SEPARATOR . 'DIR',
\FilesystemIterator::CURRENT_AS_FILEINFO |
\FilesystemIterator::KEY_AS_PATHNAME |
\FilesystemIterator::SKIP_DOTS
),
\RecursiveIteratorIterator::SELF_FIRST
);
$iterator = new ExcludeFileFilterIterator($iterator);
echo '<pre>';
foreach ($iterator as $key => $node) {
var_dump($node->getFilename());
}
echo '</pre>';
<?php
namespace Acme;
$iterator = new \RecursiveIteratorIterator(
new \RecursiveDirectoryIterator(
sprintf('glob://%s%sDIR%sDIR-1*', __DIR__, DIRECTORY_SEPARATOR, DIRECTORY_SEPARATOR),
\FilesystemIterator::CURRENT_AS_FILEINFO |
\FilesystemIterator::KEY_AS_PATHNAME |
\FilesystemIterator::SKIP_DOTS
),
\RecursiveIteratorIterator::SELF_FIRST
);
echo '<pre>';
foreach ($iterator as $key => $node) {
var_dump($node->getFilename());
}
echo '</pre>';
<?php
namespace Acme;
$iterator = new \RecursiveIteratorIterator(
new \RecursiveDirectoryIterator('phar://silex.phar/',
\FilesystemIterator::CURRENT_AS_FILEINFO |
\FilesystemIterator::KEY_AS_PATHNAME |
\FilesystemIterator::SKIP_DOTS
),
\RecursiveIteratorIterator::LEAVES_ONLY
);
foreach ($iterator as $key => $node) {
echo sprintf('<h1>%s</h1>',
htmlspecialchars($node->getFilename(), ENT_QUOTES, 'UTF-8'));
echo sprintf('<h2>%s</h2>',
htmlspecialchars($node->getPathname(), ENT_QUOTES, 'UTF-8'));
highlight_string(file_get_contents($key)); // FilesystemIterator::KEY_AS_PATHNAMEを指定してるのでキーでもOK
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment