Lorenzo Alberton

London, UK   ·   Contact me   ·  

« Articles

PHP 5.3 SPL goodies: GlobIterator, SplFileObject and CSV files

Abstract: A sneak peak at some SPL goodies introduced in PHP 5.3: The GlobIterator and SplFileObject classes.


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:

<?php
//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:

<?php
$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
    // ...
    $file->next();
}
?>

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




Related articles

Latest articles

Filter articles by topic

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


Back