PHP数据流处理与管道技术
2026/6/7 9:21:56 网站建设 项目流程

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);
?>

流过滤器可以实时转换数据。

```php
class 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);
?>
>

管道模式的流式处理。

```php
function 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的数据处理能力。

需要专业的网站建设服务?

联系我们获取免费的网站建设咨询和方案报价,让我们帮助您实现业务目标

立即咨询