PHP 5.3 SPL goodies: GlobIterator, SplFileObject and CSV files

PHP 5.3 and SPL GlobIterator

This week I upgraded to PHP 5.3-dev and had some fun with the latest SPL additions. I had a lot of files in one dir, and had to work on those matching a certain pattern. The classical glob() problem. I saw in the PHP 5.3 NEWS file that GlobIterator was added to SPL, and tried it. Even if it's not documented yet, its usage is really simple, you can use it as any other DirectoryIterator:

//search all the .txt files starting with "a":
$dir = '/some/dir/a*.txt';
$files = new GlobIterator($dir);
foreach ($files as $file) {
    echo $file->getPathname();

That's it. $file is a DirectoryIterator object, which extends SplFileInfo, so all the relative methods (like getATime(), getSize(), isFile(), etc.) are available.

SplFileObject and CSV files

I also tried SplFileObject as a CSV iterator/parser instead of the old fgetcsv(), and again working with it is very simple:

$file = new SplFileObject('/path/to/file.csv');
$delimiter = ';';
$enclosure = "\n";
$file->setCsvControl($delimiter, $enclosure);
while ($file->valid()) {
    $data = $file->fgetcsv();
    // data is an array with the values of each field of the current line
    // ...

The SPL family is getting every day more useful and convenient!

Lorenzo Alberton

Lorenzo Alberton Lorenzo has been working with large enterprise UK companies for the past 10+ years and is currently CTO at DataSift. He's an international conference speaker and a long-time contributor to many open source projects. Lorenzo Alberton's profile on GitHub Lorenzo Alberton's profile on LinkedIN View Lorenzo Alberton's profile on PHP PEAR
View Lorenzo Alberton's Twitter stream Lorenzo Alberton - Sun Certified MySQL 5 Developer PHP5 ZCE - Zend Certified Engineer


AJAX, Apache, Book Review, Charset, Cheat Sheet, Data structures, Database, Firebird SQL, Hadoop, Imagick, INFORMATION_SCHEMA, JavaScript, Kafka, Linux, Message Queues, mod_rewrite, Monitoring, MySQL, NoSQL, Oracle, PDO, PEAR, Performance, PHP, PostgreSQL, Profiling, Scalability, Security, SPL, SQL Server, SQLite, Testing, Tutorial, TYPO3, Windows, Zend Framework

Buy me a book - The Best Software Writing 1