
PHP数据流处理与管道技术数据流可以处理任意大小的数据内存占用固定。PHP的流体系很强大。今天说说流式处理和管道技术。PHP的流使用统一的协议格式。php$handle fopen(php://temp, r);fwrite($handle, Hello Stream!\n);fwrite($handle, 第二行\n);rewind($handle);while (($line fgets($handle)) ! false) {echo 读取: . trim($line) . \n;}fclose($handle);?流过滤器可以实时转换数据。phpclass UpperCaseFilter extends php_user_filter{public function filter($in, $out, $consumed, $closing): int{while ($bucket stream_bucket_make_writeable($in)) {$bucket-data strtoupper($bucket-data);$consumed $bucket-datalen;stream_bucket_append($out, $bucket);}return PSFS_PASS_ON;}}stream_filter_register(uppercase, UpperCaseFilter::class);$handle fopen(php://memory, r);stream_filter_append($handle, uppercase);fwrite($handle, hello world\n);rewind($handle);echo fread($handle, 1024);fclose($handle);?管道模式的流式处理。phpfunction createReadStream(string $path): callable{return function () use ($path) {$handle fopen($path, r);while (($line fgets($handle)) ! false) yield trim($line);fclose($handle);};}function createTransform(callable $fn): callable{return function (iterable $input) use ($fn): Generator {foreach ($input as $item) yield $fn($item);};}function createFilter(callable $predicate): callable{return function (iterable $input) use ($predicate): Generator {foreach ($input as $item) if ($predicate($item)) yield $item;};}function pipe(iterable $source, callable ...$transforms): Generator{$result $source;foreach ($transforms as $t) $result $t($result);return $result;}$source function () {foreach (range(1, 20) as $i) yield item_$i;};$result pipe($source(),createFilter(fn($v) (int)substr($v, 5) % 2 0),createTransform(fn($v) strtoupper($v)),);foreach ($result as $v) echo $v ;echo \n;?php://input和php://output在Web开发中很实用。php// 读取请求体$rawBody file_get_contents(php://input);// 写入响应$output fopen(php://output, w);fwrite($output, 直接输出\n);fclose($output);?PHP的流系统是一个强大但被低估的功能。用统一的接口处理文件、网络、内存等各种数据源在处理大数据时特别有用。自定义流封装器和过滤器可以扩展PHP的数据处理能力。