Skip to content

Instantly share code, notes, and snippets.

@mattattui
Last active December 15, 2015 04:19
Show Gist options
  • Save mattattui/5201092 to your computer and use it in GitHub Desktop.
Save mattattui/5201092 to your computer and use it in GitHub Desktop.
Using SPLFileInfo, DirectoryIterator, and php://temp
<?php
$dir = new DirectoryIterator('/Users/matt/Projects/Domain-Calendar');
$files = new RegexIterator($dir, '/^composer/');
foreach($files as $file) {
echo $file->getPathName().PHP_EOL;
}
<?php
// Fake dataset - imagine this was bigger
$data = [
['id','Name', 'Type'],
['1', 'Orange', 'Fruit'],
['2', 'Cheese', 'Dairy comestible'],
];
// Build CSV
$file = new SPLTempFileObject();
foreach ($data as $row) {
$file->fputcsv($row);
}
// Display it
header('Content-type: text/csv; charset=utf-8');
$file->rewind();
$file->fpassthru();
<?php
$info = new SPLFileInfo('/Users/matt/Projects/Domain-Calendar/README.md');
// Prints 'README.md'
echo $info->getFilename().PHP_EOL;
// Prints /Users/matt/Projects/DomainCalendar
echo $info->getPath().PHP_EOL;
// Prints '/Users/matt/Projects/DomainCalendar/README.md'
echo $info->getPathName().PHP_EOL;
// Prints bool(false)
var_dump($info->isDir());
// Returns an SPLFileObject
$file = $info->openFile('r');
// Prints each line with its line number
foreach ($file as $line_num => $line) {
// Note that $line includes the line-ending
echo "$line_num: $line";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment