从 PHP 脚本打印/回显到控制台
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20402453/
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
Printing / Echoing To Console from PHP Script
提问by AlbertEngelB
I'm debugging a PHP script that runs a couple SQL queries and emails a set of users. I'm sure this is a very basic thing, but every time I try to echo, print, or print_r it doesn't appear while running the script.
我正在调试运行几个 SQL 查询并向一组用户发送电子邮件的 PHP 脚本。我确信这是一件非常基本的事情,但是每次我尝试 echo、print 或 print_r 时,它都不会在运行脚本时出现。
So say I have this in the script:
所以说我在脚本中有这个:
print("This should print");
echo "on the command line";
When I run the script via command line php script.phpit doesn't actually print anything to the command line while running the script.
当我通过命令行运行脚本时,php script.php它实际上并没有在运行脚本时向命令行打印任何内容。
Is there a way of having PHP print to console? I feel like I'm missing something extremely basic here.
有没有办法让 PHP 打印到控制台?我觉得我在这里缺少一些非常基本的东西。
采纳答案by exussum
Thats the method of doing it.
这就是这样做的方法。
Things to check for are output buffering http://php.net/manual/en/function.ob-flush.php
要检查的事情是输出缓冲 http://php.net/manual/en/function.ob-flush.php
Is that code actually being run ? Make sure it doesnt branch before it gets there
该代码实际上正在运行吗?确保它在到达那里之前没有分支
回答by geliba187
I know it is old, but I am going post my own solution to this just in case if someone would run into similar situation. I had a problem that a legacy command line PHP script wouldn't print or echo anything to the terminal when DSN is incorrectly configured and the script got stuck for very long time (not sure how long, never waited for it to terminate by itself). After putting ob_end_flush() in the entry line of the script, the output came back to the terminal. So it turned out that all output was buffered and since the script stuck at some point, the output stayed buffered and so never went to the terminal.
我知道它很旧,但我会发布我自己的解决方案,以防万一有人遇到类似的情况。我有一个问题,当 DSN 配置不正确并且脚本卡住很长时间(不知道多长时间,从来没有等待它自行终止)时,遗留命令行 PHP 脚本不会打印或回显任何内容到终端. 将 ob_end_flush() 放入脚本的入口行后,输出返回到终端。所以结果证明所有输出都被缓冲了,因为脚本在某个时候卡住了,输出保持缓冲,所以从来没有到终端。
回答by Tiago Gouvêa
A good approach could be:
一个好的方法可能是:
function log($message)
{
$message = date("H:i:s") . " - $message - ".PHP_EOL;
print($message);
flush();
ob_flush();
}
It will output to your terminal each line you call. Just use :
它会将您呼叫的每一行输出到您的终端。只需使用:
log("Something");
log("Another line");
回答by Anvesh
The following code working fine for me.
以下代码对我来说工作正常。
<?php
print("This should print");
echo "on the command line";
?>
with tags.
带标签。

