5

My goal is to print an updating progress percentage to the console (in both Linux and Windows). Currently I just print out the percentage each 10%, but I would prefer that it updated itself every 1% without filling the screen with percentages.

Is it possible to remove text you have written to the console in PHP?

Hubro
  • 56,214
  • 69
  • 228
  • 381
  • 1
    Alternatively use `print "17%\r";`. If you use carriage return `\r` instead of newline `\n`, the cursor will be placed at the beginning of the line, which allows the next output to overwrite it. – mario May 22 '11 at 19:06
  • mario: Thanks! That answers a question I haven't asked yet :-) – Hubro May 22 '11 at 21:31

4 Answers4

3
echo chr(8);

will print a backspace character.

Oswald
  • 31,254
  • 3
  • 43
  • 68
2

very simple Note the example below

$removeLine = function (int $count = 1) {
    foreach (range(1,$count) as $value){
        echo "\r\x1b[K"; // remove this line
        echo "\033[1A\033[K"; // cursor back
    }
};

echo "-----------------------------\n";
echo "---------  Start  -----------\n";
echo "-----------------------------\n";
sleep(2);
$removeLine(3);

echo 'hi';
sleep(2);
$removeLine();

echo 'how are you ?';
die();
BlackHammer
  • 91
  • 1
  • 3
0

See Zend_ProgressBar

Alex Howansky
  • 50,515
  • 8
  • 78
  • 98
0

PEAR's Console_ProgressBar is useful for this sort of use case.

To clear the console entirely, you can use:

if($_SERVER['SHELL']) {
  print chr(27) . "[H" . chr(27) . "[2J";
}

which is quite a bit easier than keeping track of how many characters to backspace.

ceejayoz
  • 176,543
  • 40
  • 303
  • 368