Pro PHP- Patterns, Frameworks, Testing and More

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

$fpLoc = ftell($this->fp);
$data = $this->fgetcsv();
fseek($this->fp, $fpLoc);
return (is_array($data));
}

function next() {
$this->currentLine++;
//Bump the file pointer to the next line
fgets($this->fp);
}

function rewind() {
$this->currentLine = 0;

//Reset the file pointer
fseek($this->fp, 0);

//Skip the column headers
fgets($this->fp);
}

function seek($line) {
$this->rewind();
while($this->currentLine < $line && !$this->eof()) {
$this->currentLine++;
fgets($this->fp);
}
}

}

With this class in hand, you can now read the pm.csv file by using the code presented in
Listing 11-15.

Listing 11-15. Using CSVFileObject

$it = new CSVFileObject('pm.csv');
var_dump(iterator_to_array($it));

array(8) {
[0]=>
array(3) {
["Prime Minister"]=>
string(21) "Stephen Joseph Harper"
["From"]=>
string(10) "2006-02-06"

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

Free download pdf