PHP to output string to client terminal

Summary

PHP provides several methods for outputting strings to the client terminal, extending beyond typical debugging functions. Developers commonly use direct output functions like echo, print, and printf for displaying information. For stream-based output, php://output allows writing to the output buffer using functions such as file_put_contents() or fopen/fwrite. Additionally, system and passthru can execute external commands, including 'echo', to display their output. The exit or die constructs can also output a string before terminating the script, with each method offering suitability for different development or testing scenarios.

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.

1. echo

First comes with the most common one : echo.

$str = "Hello PHP\n";

echo $str;

2. print

Then comes another common one : print.

$str = "Hello PHP\n";

print $str;

3. php://output

Also we can use file_put_contents() to achieve the same.

$str = "Hello PHP\n";

file_put_contents("php://output", $str);

According to PHP manualphp://output is a write-only stream that allows you to write to the output buffer mechanism in the same way as print and echo.

Here is one variation of the above one.

$str = "Hello PHP\n";

$fp = fopen('php://output', 'w');
fwrite($fp, $str);
fclose($fp);

4. printf

You can also use the formatted version of print if you like.

$str = "Hello PHP\n";

printf($str);

5. system

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.

6. passthru

A less well know function. Passthru will execute an external program and display raw output. 

$str = "Hello PHP\n";

passthru("echo ".$str);

7. exit

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?

PHP TRICKS DEBUG OUTPUT

  RELATED

  COMMENTS

0

No comment for this article.