如何在php中处理stdin到stdout? [英] How to process stdin to stdout in php?

查看:24
本文介绍了如何在php中处理stdin到stdout?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个简单的 php 脚本来从 stdin 获取数据,对其进行处理,然后将其写入 stdout.我知道 PHP 可能不是这种事情的最佳语言,但是我需要现有的功能.

I'm trying to write a simple php script to take in data from stdin, process it, then write it to stdout. I know that PHP is probably not the best language for this kind of thing, but there is existing functionality that I need.

我试过了

<?php
$file = file_get_contents("php://stdin", "r");
echo $file;
?>

但它不起作用.我这样调用它: echo -e "\ndata\n" |php 脚本.php |猫.并且不会收到错误消息.我正在尝试构建的脚本实际上将成为更大管道的一部分.

but it doesn't work. I'm invoking it like this: echo -e "\ndata\n" | php script.php | cat. and get no error messages. The script I'm trying to build will actually be part of a larger pipeline.

关于为什么这不起作用的任何线索?

Any clues as to why this is not working?

PS:我对 PHP 不是很有经验.

PS: I'm not very experienced with PHP.

推荐答案

如果您在进行管道传输,您将希望缓冲输入,而不是一次处理所有输入,而是按照 * 的标准一次处理一行nix 工具.

If you are piping, you will want to buffer the input, instead of processing it all at once, just go one line at a time as is standard for *nix tools.

文件顶部的 SheBang 允许您直接执行文件,而不必在命令行中调用 php.

The SheBang on top of the file allows you to execute the file directly, instead of having to call php in the command line.

将以下内容保存到test.php并运行

Save the following to test.php and run

cat test.php | ./test.php

查看结果.

#!php
<?php
$handle = fopen('php://stdin', 'r');
$count = 0;
while(!feof($handle)) {
    $buffer = fgets($handle);
    echo $count++, ": ", $buffer;
}
fclose($handle);

这篇关于如何在php中处理stdin到stdout?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆