簡體   English   中英

從 PHP 中的 popen 打印出一行到屏幕?

[英]Printing out one line to screen from popen in PHP?

我正在 PHP 中創建一個批量下載站點。 我正在解析輸入,對其進行驗證,然后將其傳遞給 bash 腳本。 我將 output 輸送到 web 頁面,但網頁內容顯示如下。

8lX0JsBi.part01.rar: 0.00% - 0 bytes of 1000.0?MiB
8lX0JsBi.part01.rar: 0.09% - 917.7?KiB (939752 bytes) of 1000.0?MiB (916.7?KiB/s)
8lX0JsBi.part01.rar: 0.63% - 6.3?MiB (6566240 bytes) of 1000.0?MiB (5.3?MiB/s)
8lX0JsBi.part01.rar: 1.38% - 13.8?MiB (14430560 bytes) of 1000.0?MiB (7.0?MiB/s)
8lX0JsBi.part01.rar: 2.30% - 23.0?MiB (24129888 bytes) of 1000.0?MiB (9.0?MiB/s)

我希望它一次只顯示一行更新一行。

8lX0JsBi.part01.rar: 2.30% - 23.0?MiB (24129888 bytes) of 1000.0?MiB (9.0?MiB/s)

這是我正在使用的 function 到網頁的 pipe 標准輸出。

<?php
/**
 * Execute the given command by displaying console output live to the user.
 *  @param  string  cmd          :  command to be executed
 *  @return array   exit_status  :  exit status of the executed command
 *                  output       :  console output of the executed command
 */
function liveExecuteCommand($cmd)
{

    while (@ ob_end_flush()); // end all output buffers if any

    $proc = popen("$cmd 2>&1 ; echo Exit status : $?", 'r');

    $live_output     = "";
    $complete_output = "";

    while (!feof($proc))
    {
        $live_output     = fread($proc, 4096);
        $complete_output = $complete_output . $live_output;
        echo "$live_output";
        @ flush();
    }

    pclose($proc);

    // get exit status
    preg_match('/[0-9]+$/', $complete_output, $matches);

    // return exit status and intended output
    return array (
                    'exit_status'  => intval($matches[0]),
                    'output'       => str_replace("Exit status : " . $matches[0], '', $complete_output)
                 );
}
?>

你有幾個選擇:

使用 clear,雖然這會清除整個控制台。

system('clear');
echo '5%';
sleep(5);
system('clear');
echo '10%';

或者使用 /r,這將替換最后打印出來的行。

echo "5%";
sleep(5);
echo "\r10%";

您還可以使用 cursor 操作和字符計數或 output 緩沖區。 但我認為這會有點多。

暫無
暫無

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

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