PHP Doku:: Gibt einen oder mehrere Strings aus - function.echo.html

Verlauf / Chronik / History: (10) anzeigen

Sie sind hier:
Doku-StartseitePHP-HandbuchFunktionsreferenzTextverarbeitungZeichenkettenString-Funktionenecho

Ein Service von Reinhard Neidl - Webprogrammierung.

String-Funktionen

<<crypt

explode>>

echo

(PHP 4, PHP 5)

echoGibt einen oder mehrere Strings aus

Beschreibung

void echo ( string $arg1 [, string $... ] )

Gibt alle Parameter aus.

echo() ist nicht wirklich eine Funktion sondern ein Sprach-Konstrukt, daher brauchen Sie keine Klammern verwenden. echo() verhält sich im Gegensatz zu einigen anderen Sprach-Konstrukten nicht wie eine Funktion, deshalb kann es nicht immer in einem Funktionskontext verwendet werden. Hinzu kommt, dass bei der Angabe mehrerer Parameter für echo() diese nicht von Klammern umschlossen sein dürfen.

echo() besitzt zusätzlich eine Syntax-Kurzform, Sie können also ein öffnendes PHP-Tag von einem Gleichheitszeichen gefolgt notieren. Diese Syntax-Kurzform funktioniert nur, wenn short_open_tag in der php.ini eingeschaltet ist.

Ich habe <?=$foo?> foo.

Parameter-Liste

arg1

Der auszugebende Parameter.

...

Rückgabewerte

Es wird kein Wert zurückgegeben.

Beispiele

Beispiel #1 echo()-Beispiele

<?php
echo "Hallo Welt";

echo 
"Diese Ausgabe geht über
mehrere Zeilen. Die Zeilenumbrüche werden
ebenfalls ausgegeben."
;

echo 
"Diese Ausgabe geht über\nmehrere Zeilen. Die Zeilenumbrüche werden\nebenfalls ausgegeben.";

echo 
"Escape Zeichen werden \"so realisiert\".";

// Sie können Variablen innerhalb eines echo-Statements verwenden
$foo "foobar";
$bar "barbaz";

echo 
"foo ist $foo"// foo ist foobar

// Sie können auch Arrays nutzen
$bar = array("wert" => "foo");

echo 
"Das ist {$bar['wert']} !"// Das ist foo !

// Wenn Sie einfache Anführungszeichen verwenden, wird der Name der Variable
// anstelle ihres Inhalts ausgegeben
echo 'foo ist $foo'// foo ist $foo

// Sie können auch ausschließlich Variablen ausgeben,
// sofern Sie keine weiteren Zeichen ausgeben wollen
echo $foo;          // foobar
echo $foo,$bar;     // foobarbarbaz

// Einige Programmierer bevorzugen es, mehrere Parameter
// mithilfe von Stringverkettung auszugeben
echo 'Dieser ''String ''besteht ''aus ''mehreren Parametern.'chr(10);
echo 
'Dieser  ' 'String ' 'wurde ' 'mit ' 'Stringverkettung erzeugt.' "\n";

echo <<<END
Hier wird die "here document"-Syntax verwendet, um mehrere
Zeilen mit 
$variablen Interpolation auszugeben. Beachten Sie,
dass das sich das "here document"-Endzeichen in einer Zeile
mit nur einem Strichpunkt aber ohne Leerzeichen o.ä. stehen muss!
END;

// Da echo sich nicht wie eine Funktion verhält, ist der folgende Code ungültig.
($eine_variable) ? echo 'true' : echo 'false';

// Folgende Beispiele funktionieren hingegen:
($eine_variable) ? print 'true': print 'false' ;   // print ist ebenfalls ein
                         // Konstrukt, aber es verhält sich wie eine Funktion,
                         // so dass es in diesem Kontext verwendet werden kann
echo $eine_variable 'true''false';            // Das Statement herumgedreht
?>

Anmerkungen

Hinweis: Da dies ein Sprachkonstrukt und keine Funktion ist, können Sie dieses nicht mit Variablenfunktionen verwenden.

Siehe auch


7 BenutzerBeiträge:
- Beiträge aktualisieren...
gbarros at yahoo-inc dot com
26.01.2010 23:10
just banged my head on this missing bits on the manual.
When using the <<< method, the array keys does not require any kind of quotes.

<?php
foreach ( $data as $i ){
echo <<< END
<tr>
  <td>
$i[date]</td>
  <td>
$i[name]</td>
 </tr>
END;
}
?>

Let's hope you don't have any <?php echo $klingonships['th\'bl][ath']?> kind of array :)
Jakob Thomsen
23.11.2008 15:23
A way to color your echo output is to use shell_exec and the echo command (this only works on Linux/bash) in the following way:

<?php
echo shell_exec('echo "\e[0;31m Red color \e[0;32mGreen color \e[0m No color "');
?>

See http://wiki.archlinux.org/index.php/Color_Bash_Prompt for more colors and other options.
sandaimespaceman at gmail dot com
1.09.2008 8:25
Outputting \n won't generate a line break in the browser, <br /> is required for line break. Also,
<?php
echo "first line";
echo
"second line";
?>
will like
first linesecond line
because you didn't insert spaces/line breaks.
the echo function can also be written like
<?php
echo ('text here')
?>
nikolaas dot mennega at links dot com dot au
1.11.2007 8:04
hemanman at gmail dot com, the problem is that func() doesn't actually return a value (string or otherwise), so the result of echoing func() is null.

With the comma version, each argument is evaluated and echoed in turn: first the literal string (simple), then func(). Evaluating a function call obviously calls the function (and in this case executes its own internal echo), and the result (null) is then echoed accordingly. So we end up with "outside func() within func()" as we would expect.

Thus:

<?php
echo "outside func ()\n", func ();
?>

effectively becomes:

<?php
echo "outside func ()\n";
//func ()
{
echo
"within func ()\n";
}
echo
'';
?>

The dot version is different: there's only one argument here, and it has to be fully evaluated before it can be echoed as requested. So we start at the beginning again: a literal string, no problem, then a concatenator, then a function call. Obviously the function call has to be evaluated before the result can be concatenated with the literal string, and THAT has to happen BEFORE we can complete the echo command. But evaluating func() produces its own call to echo, which promptly gets executed.

Thus:

<?php
echo "outside func ()\n" . func ();
?>

effectively becomes:

<?php
//func ()
{
echo
"within func ()\n";
}
echo
"outside func ()\n" . '';
?>
Jason Carlson - SiteSanity
16.05.2005 19: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);
  }
}
?>
ryan at wonko dot com
27.02.2005 9: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;
}
?>
zombie)at(localm)dot(org)
25.01.2003 20: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.



PHP Powered Diese Seite bei php.net
The PHP manual text and comments are covered by the Creative Commons Attribution 3.0 License © the PHP Documentation Group - Impressum - mail("TO:Reinhard Neidl",...)