PHP to output string to client terminal
It is a common task to echo messages to the user using PHP. There are lots of ways where the message can be echoed to the client terminal(browser or console window) through PHP. These includes some well know debug methods like var_dump() and var_export() etc. In this post, we will show you some other methods shared by Laruence, one of the core members of PHP development team.
First comes with the most common one : echo.
$str = "Hello PHP\n"; echo $str;
Then comes another common one : print.
$str = "Hello PHP\n"; print $str;
Also we can use file_put_contents() to achieve the same.
$str = "Hello PHP\n"; file_put_contents("php://output", $str);
Here is one variation of the above one.
$str = "Hello PHP\n"; $fp = fopen('php://output', 'w'); fwrite($fp, $str); fclose($fp);
You can also use the formatted version of print if you like.
$str = "Hello PHP\n"; printf($str);
Apparently, you should not forget about the system function which looks a bit tricky.
$str = "Hello PHP\n"; system("echo ".$str);
system will execute the command passed in.and display the output.
A less well know function. Passthru will execute an external program and display raw output.
$str = "Hello PHP\n"; passthru("echo ".$str);
You can also use exit() to print out some string.
$str = "Hello PHP\n"; exit($str);
die() can be sued to achieve the same. These calls should be invoked as the last statement in your program.
These methods notably suit in different situations. You can choose accordingly which one to use in your application development or testing.
What other tricks do you know about?
Is this car fully tested? Or is it doing the Ice Bucket Challenge for ALS?