Pro PHP- Patterns, Frameworks, Testing and More

(vip2019) #1

(^172) CHAPTER 11 ■ SPL FILE AND DIRECTORY HANDLING
and an object-oriented approach as an alternative to the linear approach typically found in
PHP applications.
SplFileObject is also an iterator and is seekable, which allows you to use the contents of
files with the foreach loop.


File Iteration.


First, let’s look at basic line-by-line iteration. Create a CSV file like the one shown in Listing 11-11.

Listing 11-11. Sample CSV File (pm.csv)

"Prime Minister",From,To
"Stephen Joseph Harper",2006-02-06,
"Paul Edgar Philippe Martin",2003-12-12,2006-02-05
"Joseph Jacques Jean Chrétien",1993-11-04,2003-12-11
"Kim Campbell",1993-06-25,1993-11-03
"Martin Brian Mulroney",1984-09-17,1993-06-24
"John Napier Turner",1984-06-30,1984-09-16
"Pierre Elliott Trudeau",1980-03-03,1984-06-29
"Charles Joseph Clark",1979-06-04,1980-03-02

Now, you can iterate this data simply by using a foreach statement like the one shown in
Listing 11-12.

Listing 11-12. Line-by-Line Iteration

$it = new SplFileObject('pm.csv');

foreach($it as $line) {
echo $line;
}

So, that’s pretty useful. But what if you want to actually read that CSV data in a loop and
access each entry as an array?

CSV Operation.


The CSV operation of SplFileObject is particularly useful as it allows you to interpret data as
you parse it. Listing 11-13 shows CSV parsing operation.

Listing 11-13. CSV Parsing

$it = new SplFileObject('pm.csv');

while($array = $it->fgetcsv()) {
var_export($array);
}

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

Free download pdf