如何在 php 中使用 STDOUT
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8781906/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to use STDOUT in php
提问by Malloc
I am running into a project that read a stream from a txt file, so in the CLI, i write:
我遇到了一个从 txt 文件读取流的项目,因此在 CLI 中,我写道:
cat texte.txt|php index.php
In my index.php
file i read the stream:
在我的index.php
文件中,我读取了流:
$handle = fopen ("php://stdin","r");
Now i have a $result
that contains the result of my processing file and i want to output it with STDOUT
, I looked in the manual, but I don't know how to use it, can you please make me a use example.
现在我有一个$result
包含我的处理文件的结果,我想用 输出它STDOUT
,我看了手册,但我不知道如何使用它,请你给我一个使用示例。
回答by mario
Okay, let me give you another example for the STDIN
and STDOUT
usage.
In PHP you use these two idioms:
在 PHP 中,您使用这两个习语:
$input = fgets(STDIN);
fwrite(STDOUT, $output);
When from the commandline you utilize them as such:
当您从命令行使用它们时:
cat "input.txt" | php script.php > "output.txt"
php script.php < input.txt > output.txt
echo "input..." | php script.php | sort | tee output.txt
That's all these things do. Piping in, or piping out. And the incoming parts will appear in STDIN
, whereas your output should go to STDOUT
. Never cross the streams, folks!
这就是所有这些事情。管道输入,或管道输出。传入的部分将出现在 中STDIN
,而您的输出应转到STDOUT
。永远不要越过溪流,伙计们!
回答by Gordon
The constants STDIN
and STDOUT
are already resources, so all you need to do is
常量STDIN
和STDOUT
已经是资源,所以你需要做的就是
fwrite(STDOUT, 'foo');
See http://php.net/manual/en/wrappers.php
见http://php.net/manual/en/wrappers.php
php://stdin, php://stdout and php://stderr allow direct access to the corresponding input or output stream of the PHP process. The stream references a duplicate file descriptor, so if you open php://stdin and later close it, you close only your copy of the descriptor-the actual stream referenced by STDIN is unaffected. Note that PHP exhibited buggy behavior in this regard until PHP 5.2.1. It is recommended that you simply use the constants STDIN, STDOUT and STDERR instead of manually opening streams using these wrappers.
php://stdin、php://stdout 和 php://stderr 允许直接访问 PHP 进程的相应输入或输出流。该流引用了一个重复的文件描述符,因此如果您打开 php://stdin 然后关闭它,您只会关闭描述符的副本 - STDIN 引用的实际流不受影响。请注意,在 PHP 5.2.1 之前,PHP 在这方面表现出错误行为。建议您简单地使用常量 STDIN、STDOUT 和 STDERR,而不是使用这些包装器手动打开流。
回答by Gordon
this should work for you
这应该适合你
$out = fopen('php://output', 'w'); //output handler
fputs($out, "your output string.\n"); //writing output operation
fclose($out); //closing handler