Update Command-line Output, i.e. for Progress

PhpCommand LineStdoutAutoflush

Php Problem Overview


I'd like to be able to show a progress meter in a simple PHP script on the command line. Instead of seeing

Progress: 0%
Progress: 1%
etc...

I'd like just the number to change, and replace the previous number, much like git clone does for example Resolving deltas: 100% (8522/8522), done..

While searching for this I found the same question answered in Perl, which is perfect, but I couldn't find it in PHP. Is it possible? If not, I'll resort to C.

Thanks

Update: If anyone's interested in the C++ version, it's here.

Php Solutions


Solution 1 - Php

This can be done using ANSI Escape Sequences -- see here for a list.

In PHP, you'll use "\033" when it's indicated ESC on that page.


In your case, you could use something like this :

echo "Progress :      ";  // 5 characters of padding at the end
for ($i=0 ; $i<=100 ; $i++) {
    echo "\033[5D";      // Move 5 characters backward
    echo str_pad($i, 3, ' ', STR_PAD_LEFT) . " %";    // Output is always 5 characters long
    sleep(1);           // wait for a while, so we see the animation
}


I simplified a bit, making sure I always have 5 extra characters, and always displaying the same amount of data, to always move backwards by the same number of chars...

But, of course, you should be able to do much more complicated, if needed ;-)

And there are many other interesting escape sequences : colors, for instance, can enhance your output quite a bit ;-)

Solution 2 - Php

Just for the record though an old thread: Instead of using fancy ANSI Escape sequencing to move the curser back I just move it back to the beginning of the line using "\r" instead of to the beginning of the next line "\n". Add a few spaces after your echo to overwrite anything that was there previously, like e.g. so:

for ($i=0 ; $i<=100 ; $i++) {
  echo "Progress: $i %   \r";
  sleep(1);
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAdamView Question on Stackoverflow
Solution 1 - PhpPascal MARTINView Answer on Stackoverflow
Solution 2 - PhpDomView Answer on Stackoverflow