 |
echo (PHP 3, PHP 4, PHP 5) echo -- Output one or more strings Descriptionvoid echo ( string arg1 [, string ...] )
Outputs all parameters.
echo() is not actually a function (it is a
language construct), so you are not required to use parentheses
with it. echo() (unlike some other language
constructs) does not behave like a function, so it cannot
always be used in the context of a function. Additionally, if you want to
pass more than one parameter to echo(), the parameters
must not be enclosed within parentheses.
例子 1. echo() examples
<?php echo "Hello World";
echo "This spans multiple lines. The newlines will be output as well";
echo "This spans\nmultiple lines. The newlines will be\noutput as well.";
echo "Escaping characters is done \"Like this\".";
// You can use variables inside of an echo statement $foo = "foobar"; $bar = "barbaz";
echo "foo is $foo"; // foo is foobar
// You can also use arrays $bar = array("value" => "foo");
echo "this is {$bar['value']} !"; // this is foo !
// Using single quotes will print the variable name, not the value echo 'foo is $foo'; // foo is $foo
// If you are not using any other characters, you can just echo variables echo $foo; // foobar echo $foo,$bar; // foobarbarbaz
// Some people prefer passing multiple parameters to echo over concatenation. echo 'This ', 'string ', 'was ', 'made ', 'with multiple parameters.', chr(10); echo 'This ' . 'string ' . 'was ' . 'made ' . 'with concatenation.' . "\n";
echo <<<END This uses the "here document" syntax to output multiple lines with $variable interpolation. Note that the here document terminator must appear on a line with just a semicolon. no extra whitespace! END;
// Because echo does not behave like a function, the following code is invalid. ($some_var) ? echo 'true' : echo 'false';
// However, the following examples will work: ($some_var) ? print 'true' : print 'false'; // print is also a construct, but // it behaves like a function, so // it may be used in this context. echo $some_var ? 'true': 'false'; // changing the statement around ?>
|
|
echo() also has a shortcut syntax, where you can
immediately follow the opening tag with an equals sign. This short syntax
only works with the short_open_tag configuration setting
enabled.
For a short discussion about the differences between
print() and echo(), see this FAQTs
Knowledge Base Article: http://www.faqts.com/knowledge_base/view.phtml/aid/1/fid/40
注: 由于这是一个语言结构而非函数,因此它无法被变量函数调用。
See also
print(),
printf(), and
flush().
phpnet at i3x171um dot com
21-May-2006 10:39
I have written a script to benchmark the several methods of outputting data in PHP: via single quotes, double quotes, heredoc, and printf. The script constructs a paragraph of text with each method. It performs this construction 10,000 times, then records how long it took. In total, it prints 160,000 times and records 16 timings. Here are the raw results.
Outputted straight to browser--
Single quotes: 2,813 ms
...with concatenation: 1,179 ms
Double quotes: 5,180 ms
...with concatenation: 3,937 ms
heredoc: 7,300 ms
...with concatenation: 6,288 ms
printf: 9,527 ms
...with concatenation: 8,564 ms
Outputted to the output buffer--
Single quotes: 8 ms
...with concatenation: 38 ms
Double quotes: 8 ms
...with concatenation: 47 ms
heredoc: 17 ms
...with concatenation: 49 ms
printf: 54 ms
...with concatenation: 52 ms
A nice graph of the script's output can be found here:
http://i3x171um.com/output_benchmarks/ob.gif
So what should you choose to print your text? I found several things out writing this.
First, it should be noted that the print and echo keywords are interchangeable, performance-wise. The timings show that one is probably an alias for the other. So use whichever you feel most comfortable with.
Second, if you've ever wondered which was better, the definitive answer is single quotes. Single quotes are at least four times faster in any situation. Double quotes, while more convenient, do pose a debatably significant performance issue when outputting massive amounts of data.
Third, stay away from heredoc, and absolutely stay away from [s]printf. They're slow, and the alternatives are there.
The source of my script can be found here:
http://i3x171um.com/output_benchmarks/ob.txt
DO NOT RUN THE SCRIPT ON THE INTERNET! Run it instead from localhost. The script outputs ~45 megabytes of text in an html comment at the top of the page by default. Expect the benchmark to take ~45 seconds. If this is too long, you can change the amount of iterations to a lower number (the results scale accurately down to about 1,000 iterations).
bennyhur at gmail dot com
02-Feb-2006 03:39
in response to:
"This is a beauty for lots of text, really. And easy to read, if you're a PERL or shell person."
If you use an editor like Dreamweaver that can show you a somewhat rendered version of the page, you can output large blocks of text/html by doing the following:
<?php
if(boolean_function())
{
?>
<p>You successfully made the boolean funciton return true</p>
<p>blah blah blah....</p>
<?php
}
else
{
?>
<p>Sorry, but you didnt make the boolean true!</p>
<?php
}
//more code...
?>
As opposed to using the "dochere" syntax. I find it's much easier to move around in large scripts when I output HTML like this because I can just click on the text near the code I need to edit in Dreamweavers display view, and then switch to code view and I'm right were I need to be.
rwruck
28-Jan-2006 05:15
It should be mentioned here that the script will be aborted if you output something in response to a HTTP HEAD request.
In the following example, the second line will NOT be written to the file. Any registered shutdown function will be called, though:
<?php
$hf = fopen('head.log', 'ab');
fwrite($hf, "before output\n");
echo "Test";
fwrite($hf, "after output\n");
fclose($hf);
?>
This is normal behaviour; see the description of $_SERVER.
the dot only dot storm at gmail dot com
07-Jan-2006 04:38
In reply to lorenpr at gmail dot com:
"I hope this ternary thing isn't overkill. Last thing - I would just like to make you aware of the side effect when you do this statement,
<?php
echo $some_var ? print 'true': print 'false';
?>
The result would be either 'true1' or 'false1', depending on whether $some_var is true or false respectively. This happens because of what I mentioned earlier. Figure it out."
The reason it prints the 1 because whether the variable is true or false, in this case, print will always return 1 (true)
Meaning this is the same thing:
<?php
echo print($some_var ? 'true' : 'false');
?>
print($some_var ? 'true' : 'false') = 1
So you echo 1, after the print takes place.
08-Oct-2005 04:09
This is a beauty for lots of text, really. And easy to read, if you're a PERL or shell person.
echo <<<END
This uses the "here document" syntax to output
multiple lines with $variable interpolation. Note
that the here document terminator must appear on a
line with just a semicolon. no extra whitespace!
END;
lorenpr at gmail dot com
15-Sep-2005 12:12
I hope this ternary thing isn't overkill. Last thing - I would just like to make you aware of the side effect when you do this statement,
echo $some_var ? print 'true': print 'false';
The result would be either 'true1' or 'false1', depending on whether $some_var is true or false respectively. This happens because of what I mentioned earlier. Figure it out.
lorenpr at gmail dot com
15-Sep-2005 11:58
linus is correct.
The ternary relationship is evaluated first, then echo prints the result.
Also, keep in mind
(condition? a : b)
reads
if(condition) return a; else return b;
So what makes
A. echo ($somevar) ? 'true' : 'false';
different from
B. ($somevar) ? echo 'true' : echo 'false';
is the ternary relationship in A reads
if (condition) return 'true'; else return 'false';
while in B it reads
if(condition) return (echo 'true'); else return (echo 'false');
- an invalid statement, since echo evaluates to void.
linus.martensson a gmail
25-Aug-2005 05:03
Simple. it reads like echo (($somevar)?'true';'false'); and outputs the result, unless I'm mistaken.
shannonmoeller at gmail dot com
10-Aug-2005 07:31
In reply to lorenpr at gmail dot com:
If what you say is true, why does this work?
<?php
echo ($somevar) ? 'true' : 'false'; //works
?>
lorenpr at gmail dot com
29-Jul-2005 01:17
I just want to point out something to beginners. The documentation is misleading where it says:
// Because echo is not a function, following code is invalid.
($some_var) ? echo 'true' : echo 'false';
The code is invalid, but not because 'echo' is a language construct, but rather because 'echo' does not return a value.
So don't be mislead: the syntax used above is certainly not limited to functions.
You must keep in mind that the job of the ternary syntax used is not actually to display anything, but to test a boolean relationship. The 'print' statement would work because it always returns a 1, which in php, is interpreted to a boolean 'true'. Things that return 'void' cannot be expected to evaluate to a 'true' or 'false', and that is why using 'echo' in this particular case is invalid.
Jason Carlson - SiteSanity
17-May-2005 01:28
In response to Ryan's post with his echobig() function, using str_split wastes memory resources for what you are doing.
If all you want to do is echo smaller chunks of a large string, I found the following code to perform better and it will work in PHP versions 3+
<?php
function echobig($string, $bufferSize = 8192)
{
// suggest doing a test for Integer & positive bufferSize
for ($chars=strlen($string)-1,$start=0;$start <= $chars;$start += $bufferSize) {
echo substr($string,$start,$buffer_size);
}
}
?>
renrutal at gmail dot com
29-Mar-2005 07:34
Note that:
<?php
echo "2 + 2 = " . 2+2; // This will print 4
echo "2 + 2 = " , 2+2; // This will print 2+2 = 4
?>
The commas will parse the result of the expressions correctly.
paul dot mateescu at zirkonmedia dot ro
27-Feb-2005 06:35
Hello,
If you want to use echo <<<ENDOFECHO (here document style) and you notice that the server does not seem to recognise this form (you get a blank page with no content at all), chances are your editor uses a wrong type of line break.
Fore instance, I use Dreamweaver for Macintosh. You should have the following preferences:
Dreamweaver >> Preferences >> Code Format >> Line break type
set to "CR LF (Windows)" or "LF (Unix)". Dreamweaver for Mac ships with "CR (Macintosh)" by default (at least the MX edition, don't know about any other editions), which confuses the PHP interpreter.
Best,
Paul Mateescu
ryan at wonko dot com
27-Feb-2005 04:56
Due to the way TCP/IP packets are buffered, using echo to send large strings to the client may cause a severe performance hit. Sometimes it can add as much as an entire second to the processing time of the script. This even happens when output buffering is used.
If you need to echo a large string, break it into smaller chunks first and then echo each chunk. The following function will do the trick in PHP5:
<?php
function echobig($string, $bufferSize = 8192)
{
$splitString = str_split($string, $bufferSize);
foreach($splitString as $chunk)
echo $chunk;
}
?>
Truffy
15-Jan-2005 05:02
You can use braces around variables as well as array items. This is useful to help recognition of your variables in your code, but most useful where the variable iteslf cannot be separated with spaces from the preceding/following code, for exmple in a file path:
If a path is assigned the variable $path, then this code will not work:
echo "$pathindex.php";
whereas this will
echo "{$path}index.php";
zombie)at(localm)dot(org)
26-Jan-2003 03:26
[Ed. Note: During normal execution, the buffer (where echo's arguments go) is not flushed (sent) after each write to the buffer. To do that you'd need to use the flush() function, and even that may not cause the data to be sent, depending on your web server.]
Echo is an i/o process and i/o processes are typically time consuming. For the longest time i have been outputting content by echoing as i get the data to output. Therefore i might have hundreds of echoes in my document. Recently, i have switched to concatenating all my string output together and then just doing one echo at the end. This organizes the code more, and i do believe cuts down on a bit of time. Likewise, i benchmark all my pages and echo seems to influence this as well. At the top of the page i get the micro time, and at the end i figure out how long the page took to process. With the old method of "echo as you go" the processing time seemed to be dependent on the user's net connection as well as the servers processing speed. This was probably due to how echo works and the sending of packets of info back and forth to the user. One an one script i was getting .0004 secs on a cable modem, and a friend of mine in on dialup was getting .2 secs. Finally, to test that echo is slow; I built strings of XML and XSLT and used the PHP sablotron functions to do a transformation and return a new string. I then echoed the string. Before the echo, the process time was around .025 seconds and .4 after the echo. So if you are big into getting the actual processing time of your scripts, don't include echoes since they seem to be user dependent. Note that this is just my experience and it could be a fluke.
|  |