Pro PHP- Patterns, Frameworks, Testing and More

(vip2019) #1
CHAPTER 11 ■ SPL FILE AND DIRECTORY HANDLING^173

array (
0 => 'Prime Minister',
1 => 'From',
2 => 'To',
)array (
0 => 'Stephen Joseph Harper',
1 => '2006-02-06',
2 => '',
)

...
array (
0 => '',
)


Listing 11-13 demonstrates parsing CSV records in numerical order, with a while loop.
This is useful, but it could be more so. You can take this another step and create a CSVFileObject
that is designed specifically for CSV operation. One thing you will have noticed from the example
in Listing 11-13 is that the CSV headers were interpreted as data and the final line was inter-
preted as a blank array. Iterating a CSV file should take these two special cases into account.
First, create an Iterator class CSVFileObject that descends from SplFileInfo. In the
constructor, call the parent SplFileInfo constructor, read the first line of the file, and assign an
array mapping the CSV indexes to the column names. Next, implement the iterator methods.
Listing 11-14 shows this CSV class.

Listing 11-14. The CSVFileObject Class

class CSVFileObject extends SPLFileInfo implements Iterator, SeekableIterator {

protected $map, $fp, $currentLine;

public function __construct( $filename,
$mode = 'r',
$use_include_path = false,
$context = NULL
)
{

parent::__construct($filename);

//Cannot pass an implicit null to fopen
if(isset($context)) {
$this->fp = fopen( $filename,
$mode,
$use_include_path,
$context
);

McArthur_819-9C11.fm Page 173 Thursday, February 28, 2008 7:49 AM

Free download pdf