簡體   English   中英

在CLI PHP腳本中使用輸出緩沖時打印到終端

[英]Printing to terminal while using output buffering in CLI PHP scripts

我正在使用命令行PHP來離線構建一些文件。 要捕獲腳本輸出,我使用標准的ob_start:

ob_start();
// Echo lots of stuff
$content = ob_get_contents();
// Now the $content can be written to a file

但是,我還想將一些消息打印到終端(例如,警告), 同時將“主輸出”收集到緩沖區中。 有沒有辦法做到這一點? 似乎暫時不能暫停緩沖以打印終端消息,然后從剩下的位置繼續緩沖。 這有什么解決方法嗎?

只需使用fputs()寫入STDOUT或STDERR(兩個包含文件指針資源的常量):

ob_start();
echo 'Output buffer';
fputs(STDOUT, "Log message");
$x = ob_get_contents();
ob_end_clean();;

echo "X = $x";

使用php://stderr流:

$f = fopen('php://stderr', 'w');
fputs($f, 'Output');

編輯:此外,在CLI中,有一個預定義的STDERR常量

fputs(STDERR, 'Output');

可以“暫停”輸出緩沖區。 將緩沖區的內容寫入變量,並在不刷新的情況下結束緩沖區。 寫一些非緩沖輸出,再次調用ob_start()。 此方法使用字符串連接,這是一種相對較臟的方法。 出於這個原因,我更喜歡我自己的其他方法。

但在任何一種情況下,這是一個小的,有效的例子:

<?php
ob_start();
    echo 'Buffered line 1.<br>';
$ob = ob_get_contents();
ob_end_clean();

echo 'Non-buffered line.<br>';

ob_start();
    echo 'Buffered line 2.<br>';
$ob .= ob_get_contents();
ob_end_clean();

echo 'Non-buffered line.<br>';

ob_start();
    echo 'Buffered line 3.<br>';
$ob .= ob_get_contents();
ob_end_clean();

echo 'Non-buffered line.<br>';

echo $ob;
?>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM