Reputation: 7774
I am writing a command line php script which does some output to the console window, its all look good only issues is when i type
php myfilename.php -....
in the console window, ONLY AFTER its fully executed it outputs the result to the window ..
Wht i want is to do this on the fly like below
customer id: 1223 skipped.
customer id: 22233 added..
...etc
another question is adding \n\r to the printf functions didn't go to a new line ...
any idea on these issues..
Upvotes: 6
Views: 20587
Reputation: 1903
About the End-Of-Line marker, always use PHP predefined constant PHP_EOL
; it is correctly set based on your platform, so you do not have to worry is it right or wrong.
For the [Enter] issue, it could be the output buffering is on. Add this simple test in your script:
function test()
{
$state = array(' added', ' skipped');
for ($i = 0; $i < 50; $i++)
{
echo 'customer id: ' . rand(1, 1000) . $state[rand(0, 1)] . PHP_EOL;
usleep(50000); // slow it a bit to see the line by line output
}
}
// without ob -------------------------------------------
$start = microtime(true);
test();
echo 'Finished in ' . round(microtime(true) - $start, 2) . PHP_EOL . str_repeat('-', 78) . PHP_EOL;
sleep(1);
// with ob ----------------------------------------------
$start = microtime(true);
ob_start(); // if called somewhere at the top in your script
// some previous code...
echo 'Line 1'.PHP_EOL.'Line 2'.PHP_EOL.uniqid().PHP_EOL;
// flush the buffer and stop ob
// this will echo whatever is in the output buffer!
//ob_end_flush();
// or, store the current buffer content in a variable and use it later
$output = ob_get_clean();
test();
echo $output;
echo 'Finished in ' . round(microtime(true) - $start, 2) . PHP_EOL . str_repeat('-', 78) . PHP_EOL;
// you could start buffering again, if needed
ob_start();
For output control functions see http://www.php.net/manual/en/ref.outcontrol.php. They are very powerful tools.
Hope it helps. Cheers!
Upvotes: 3
Reputation: 104090
First, the Windows-style end-of-line marker is \r\n
, not \n\r
. Not many systems ever used \n\r
, but they are rare enough that you can forget about them now.
Second, chances are good the output is being block buffered -- you can either use ob_implicit_flush(1)
to automatically insert a flush()
command after every output command. Or, you could call flush()
manually, when you need to flush output.
Upvotes: 5
Reputation:
This is probably due to output buffering. You can use ob_flush()
to flush the buffer manually when needed.
As for your second issue, the correct sequence for newline on Microsoft Windows is "\r\n"
, not the other way around.
Upvotes: 6