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 ...Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access