我有一个自定义过滤器,必须为资源中的每个字符串添加一个值,但方法filter()执行一次
class custom_filter extends php_user_filter
{
function filter($in, $out, &$consumed, $closing)
{
while ($bucket = stream_bucket_make_writeable($in)) {
$bucket->data = 'Test,' . $bucket->data;
$consumed += $bucket->datalen;
stream_bucket_append($out, $bucket);
}
return PSFS_PASS_ON;
}
}
我如何使用这个过滤器类,但只有第一行有价值'测试'
$source = fopen($file, 'rb');
stream_filter_register("custom_filter", "custom_filter");
stream_filter_append($source, "custom_filter", STREAM_FILTER_READ);
while (!feof($source)) {
$line = fgets($source);
}
fclose($source);
如何添加值'测试'到每一行。
答案 0 :(得分:0)
自定义php_user_filter
执行一次,因为整个文件都被读取到存储桶中。
while ($bucket = stream_bucket_make_writeable($in)) {
var_dump($bucket->data);
$consumed += $bucket->datalen;
stream_bucket_append($out, $bucket);
}
object(stdClass)#2 (3) {
["bucket"]=>
resource(10) of type (userfilter.bucket)
["data"]=>
string(N) "<all data in the file>
"
["datalen"]=>
int(N)
}
我建议打开一个单独的目标流以进行写入,并在读取源流的每一行时将其写入写入流。
stream_filter_register("custom_filter", "custom_filter");
$source = fopen('input.txt', 'rb');
$dest = fopen('output.txt', 'wb');
stream_filter_append($dest, "custom_filter", STREAM_FILTER_WRITE);
while (!feof($source)) {
$line = fgets($source);
fwrite($dest, $line);
}
fclose($source);
fclose($dest);