Creating Filters
PHP 5 comes with very few stream filters, but it introduces the ability to write your own filters in PHP, effectively giving you unlimited possibilities. PHP 4 requires all filters to be implemented in C.
The filter interface is much less complex than the wrapper interface.
It has only three different methods, and it’s common
to implement only a single method, filter( )
.
Table 8-3 contains an overview of the API.
Table 8-3. Filter methods
Method |
Description |
---|---|
|
Called during data filtering; may be called multiple times per stream |
|
Called during filter instantiation |
|
Called during filter destruction |
The filter( )
method is where all the action takes
place. Inside this method, you’re required to
process the incoming data, filter it when you can, and then alert the
filter of your progress.
This section shows how to implement two different filters: one that
encodes special characters (such as &
and
<
) to their HTML entities equivalents, and
one the does the reverse, by transforming HTML entities back into
characters.
Converting to HTML Entities
Example 8-6
shows a filter that encodes HTML entities using the
htmlentities( )
function.
Example 8-6. Encoding HTML entities with a filter
class htmlentitiesFilter extends php_user_filter { function filter($in, $out, &$consumed, $closing) { while ($bucket = stream_bucket_make_writeable($in)) { $bucket->data ...
Get Upgrading to PHP 5 now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.