phpcommand-line-interface

Clear single line of PHP CLI output


I'm trying to get a "live" progress indicator working on my php CLI app. I'm running windows 7 64 bit ultimate. Rather than outputting as

1 Done
2 Done
3 Done

I would rather it cleared the line and just showed the latest result. Running system("command \C CLS") doesnt work. Nor does ob_flush(), flush() or anything else that I've found.


Solution

  • Try outputting a line of text and terminating it with "\r" instead of "\n".

    The "\n" character is a line-feed which goes to the next line, but "\r" is just a return that sends the cursor back to position 0 on the same line.

    So you can:

    echo "1Done\r";
    echo "2Done\r";
    echo "3Done\r";
    

    etc.

    Make sure to output some spaces before the "\r" to clear the previous contents of the line.

    [Edit] Optional: Interested in some history & background? Wikipedia has good articles on "\n" (line feed) and "\r" (carriage return)