/*
I use this very handy function instead of echo most of the time. It simultaneously displays a message to the screen and a log with a datestamp. Probably only works in Windows. I only run it from the commandline, so I don't know how it would behave on a website.
*/
define('LOG_FILE', 'C:\Backups\Backup.log');
function message($message)
{
// If we forgot to add a new line to the end...
if (substr($message, -1) != "\n") {
// ...add it.
$message = $message . "\n";
}
echo $message;
// Log messages need a Windows line feed
$message = str_replace("\n", "\r\n", $message);
if (!$fh = @fopen(LOG_FILE, "a")) {
return FALSE;
}
// [January 1st, 1900 2:13:45pm] Message...
if (@fwrite($fh, "[".date("F jS, Y g:i:sa")."] ".$message)) {
@fclose($fh);
return TRUE;
} else {
@fclose($fh);
return FALSE;
}
}
echo
(PHP 4, PHP 5)
echo — Muestra una o más cadenas
Descripción
Muestra todos sus parámetros por la salida definida.
echo() no es realmente una función (es una sentencia del lenguaje) de modo que no se requiere el uso de los paréntesis. De hecho, si se indica más de un parámetro, no se pueden incluir los paréntesis.
Example #1 Ejemplos de echo()
<?php
echo "Hola Mundo";
echo "Este texto se extiende
por varias lineas. Los saltos de linea
tambien se envian";
echo "Este texto se extiende\npor varias lineas. Los saltos de linea\ntambien se envian.";
echo "Para escapar caracteres, se debe indicar \"de esta forma\".";
// Se pueden usar variables dentro de una sentencia echo
$saludo = "que tal";
$despedida = "hasta luego";
echo "hola, $saludo"; // hola, que tal
// Tambien se pueden usar arrays
$cadena = array("valor" => "saludo desde un array");
echo "Esto es un {$cadena['valor']} "; // Esto es un saludo desde un array
// Si se emplean comillas simples, se muestra el nombre de la variable, no su valor
echo 'hola, $saludo'; // hola, $saludo
// Si no se anade ningun caracter, tambien es posible emplear echo para mostrar el valor de las variables
echo $saludo; // que tal
echo $saludo,$despedida; // que talhasta luego
// El uso de echo con multiples parametros es igual que realizar una concatenacion
echo 'Esta ', 'cadena ', 'esta ', 'construida ', 'con muchos parametros.', chr(10);
echo 'Esta ' . 'cadena ' . 'esta ' . 'construida ' . 'empleando concatenacion.' . "\n";
echo <<<FIN
Este texto utiliza una sintaxis especial que
permite mostrar varias lineas de texto.
La etiqueta que indica el final del bloque de texto
(y que en este caso es "FIN") debe aparecer en una
linea que contenga solamente el valor de la etiqueta
y un caracter de punto y coma (ni siquiera puede
contener espacios en blanco).
FIN;
// Como echo no es una funcion, el siguiente codigo no es valido
($una_variable) ? echo 'verdadero' : echo 'falso';
// Sin embargo, los siguientes ejemplos si que funcionan.
($una_variable) ? print('verdadero'): print('falso'); // print es una funcion
echo $una_variable ? 'verdadero': 'false'; // se modifica la sentencia a mostrar en funcion del valor de $una_variable
?>
echo() tambié funciona con una sintaxis abreviada formada por una etiqueta de apertura seguida de un signo igual. La sintaxis abreviada solamente funciona si se encuentra habilitada la directiva de configuración short_open_tag.
Tengo <?=$numero?> unidades.
En el siguiente articulo de la "FAQTs Knowledge Base" » http://www.faqts.com/knowledge_base/view.phtml/aid/1/fid/40 puede encontrarse una argumentación sobre las diferencias entre las funciones print() y echo().
Note: Puesto que esto es una construcción del lenguaje y no una función, no puede ser llamado usando funciones variables
echo
24-Nov-2008 12:47
23-Nov-2008 06: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.
31-Aug-2008 11: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')
?>
01-Nov-2007 12: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:
<?
echo "outside func ()\n", func ();
?>
effectively becomes:
<?
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:
<?
echo "outside func ()\n" . func ();
?>
effectively becomes:
<?
//func ()
{
echo "within func ()\n";
}
echo "outside func ()\n" . '';
?>
16-May-2005 10: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);
}
}
?>
27-Feb-2005 12: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;
}
?>
25-Jan-2003 11: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.
