【问题标题】:Output two lines separately to the console in PHP在PHP中分别输出两行到控制台
【发布时间】:2016-08-22 19:22:39
【问题描述】:

我编写了这个从 0 到 9 计数的小 PHP 脚本,同时还显示了计数的总和。

<?php
$sum = 0;
$line = '';
for ($i=0; $i < 10; $i++) {
    $sum += $i;
    echo str_repeat(chr(8), strlen($line)); // cleaning the line
    $line = "Counter: {$i} | Total: {$sum}";
    echo $line; // Outputing the new line
    sleep(1);
}
echo "\n";

如您所见,在每次迭代中,我都会清理行(8backspace 的 ASCII 代码)并在同一行中显示新文本。

这很好用,但现在我想在两行不同的行中显示计数和总计,并以与我对一行相同的方式为这两行设置动画。所以我尝试了这段代码:

<?php
$sum = 0;
$line = '';
for ($i=0; $i < 10; $i++) {
    $sum += $i;
    echo str_repeat(chr(8), strlen($line)); // cleaning the line
    $line = "Counter: {$i}\nTotal: {$sum}";
    echo $line; // Outputing the new line
    sleep(1);
}
echo "\n";

这里的问题是backspace 停在\n 字符处,因此它删除了第二行,但保留了第一行,这给出了以下输出:

Counter: 0
Counter: 1
Counter: 2
Counter: 3
Counter: 4
Counter: 5
Counter: 6
Counter: 7
Counter: 8
Counter: 9
Total: 45

有没有合适的方法来解决这个问题?

谢谢

【问题讨论】:

  • echo 'something'.PHP_EOL;
  • @RiggsFolly 请在回答之前阅读完整的问题:)

标签: php command-line-interface


【解决方案1】:

我终于找到了一个可行的解决方案:

<?php
$sum = 0;
$line = '';
for ($i=0; $i < 10; $i++) {
    $sum += $i;
    $line = "Counter: {$i}\nTotal: {$sum}";
    echo $line; // Outputing the new line
    sleep(1);
    echo chr(27) . "[0G"; // go to the first column
    echo chr(27) . "[1A"; // go to the first line
    echo chr(27) . "[2M"; // remove two lines
}
echo "Total: {$sum}\n";

这得益于一些 ansicode,查看This document 了解更多详情。

感谢@Joshua Klein 的帮助。

【讨论】:

    【解决方案2】:

    真的很蹩脚的答案(适用于linux):

        <?php
    $sum = 0;
    $line = '';
    for ($i=0; $i < 10; $i++) {
        $sum += $i;
        echo str_repeat(chr(8), strlen($line)); // cleaning the line
        $line = "Counter: {$i}\nTotal: {$sum}";
        echo $line; // Outputing the new line
        sleep(1);
        system("clear");
    }
    echo "\n";
    

    真正的答案与您可以在此处阅读的 \r(换行符)或不同的 ansicodes 字符有关:
    Clear PHP CLI output

    【讨论】:

      猜你喜欢
      • 2017-08-22
      • 1970-01-01
      • 1970-01-01
      • 2011-03-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-26
      • 2013-03-18
      相关资源
      最近更新 更多