Pro PHP- Patterns, Frameworks, Testing and More

(vip2019) #1

(^176) CHAPTER 11 ■ SPL FILE AND DIRECTORY HANDLING
["To"]=>
string(0) ""
}
[1]=>
array(3) {
["Prime Minister"]=>
string(26) "Paul Edgar Philippe Martin"
["From"]=>
string(10) "2003-12-12"
["To"]=>
string(10) "2006-02-05"
}
}
Now the CSV data is converted to an array format with the keys being the CSV column
headers. This can make CSV parsing cleaner and tie the data to the column names, rather than
arbitrary array indexes. Also, the first record is no longer the headers, and the last record is the
last line of CSV data in the file.
You could apply a filter iterator to this result set to create a searchable system.


Searching Files


Using the SPL file and directory facilities, you can put together a basic text-file search system. In this
example, you will create two custom filter iterators: one based on SearchIterator, which searches
the contents of a file for a substring match and stops as soon as a match is found, and another that
invokes the search and sees if any results are returned. You will use a RecursiveDirectoryIterator
and a RecursiveIteratorIterator to get the file names to test. Listing 11-16 shows a simple
substring search using iterators.

Listing 11-16. Substring Searching with Iterators

require_once('/path/to/php-src/ext/spl/examples/searchiterator.inc');

class InFileSearch extends SearchIterator {

protected $search;

public function __construct($it, $search) {
parent::__construct($it);
$this->search = $search;
}

//If the substring is found then accept
public function accept() {
return (strpos($this->current(), $this->search) !== FALSE);
}
}

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

Free download pdf