Today's Question:  What are you most afraid of as a programmer?        GIVE A SHOUT

Technical Article => Web =>  PHP

PHP to output string to client terminal

  sonic0002      2015-10-01 03:16:56      1,063    0    0

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

  SAVE AS PDF   MARK AS READ   MARK AS IMPORTANT

Share on Facebook  Share on Twitter  Share on Google+  Share on Weibo  Share on Reddit  Share on Digg  Share on Tumblr    Delicious

  RELATED


  0 COMMENT


No comment for this article.


  WRITE ARTICLE

The status of debugging

By sonic0002