18.18. Writing to Standard Output
Problem
You want to write to standard output.
Solution
Use echo
or print
:
print "Where did my pastrami sandwich go?"; echo "It went into my stomach.";
Discussion
While print( )
is a function,
echo
is a language construct. This means that
print( )
returns a value, while
echo
doesn’t. You can include
print( )
but not echo
in larger
expressions:
// this is OK (12 == $status) ? print 'Status is good' : error_log('Problem with status!'); // this gives a parse error (12 == $status) ? echo 'Status is good' : error_log('Problem with status!');
Use php://stdout as the filename if you’re using the file functions:
$fh = fopen('php://stdout','w') or die($php_errormsg);
Writing to standard output via a file handle instead of simply with
print( )
or echo
is useful if
you need to abstract where your output goes, or if you need to print
to standard output at the same time as writing to a file. See Section 18.20 for details.
You can also write to standard error by opening php://stderr:
$fh = fopen('php://stderr','w');
See Also
Section 18.20 for writing to many filehandles
simultaneously; documentation on echo
at
http://www.php.net/echo and on print( )
at http://www.php.net/print.
Get PHP Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.