downloads | documentation | faq | getting help | mailing lists | licenses | wiki | reporting bugs | php.net sites | links | conferences | my php.net

search for in the

Instrucción separador> <Etiquetas de PHP
[edit] Last updated: Fri, 25 May 2012

view this page in

Salir de HTML

Cualquier cosa fuera del par de etiquetas de apertura y cierre es ignorado por el analizador de PHP, el cual permite los ficheros de PHP tengan contenido mixto. Esto permite que PHP sea embebido en documentos HTML, por ejemplo para crear plantillas.

<p>Esto va a ser ignorado por PHP y mostrado por el navegador.</p>
<?php echo 'Mientras que esto va a ser analizado.'?>
<p>Esto también será ignorado por PHP y mostrado por el navegador.</p>
Esto funciona como se espera, porque cuando PHP intercepta las etiquetas de cierre ?>, simplemente comienza a imprimir cualquier cosa que encuentre (a excepción de un una nueva lína inmediatamente después - véase separación de instrucciones) haste que dé con otra etiqueta de apertura a menos que se encuentre en mitad de una sentencia condicional, en cuyo caso el intérprete determinará el resultado de la condición antes de tomar una decisión de lo que tiene que saltar. Véase el siguiente ejemplo.

Usar estructuras con condiciones

Ejemplo #1 Advanced escaping using conditions

<?php if ($expresión == true): ?>
  Esto se mostrará si la expresión es verdadera.
<?php else: ?>
  En caso contrario se mostrará esto.
<?php endif; ?>
En este ejemplo PHP saltará los bloques donde la condición no se cumpla, incluso si están fuera de las etiquetas de apertura/cierre de PHP, PHP los saltará según la condición ya que el intérprete de saltará por encima de los bloques contenidos dentro de una condición que no se cumpla.

Para salir de bloques de texto grandes, es más eficiente abandonar el modo analítico de PHP que enviar todo el texto a través de echo o print.

Existen cuatro tipos de pares de etiquetas de apertura y de fin de bloque que se pueden usar en PHP. Dos de estas, <?php ?> y <script language="php"> </script>, siempre están disponibles. Las otras dos son etiquetas cortas y etiquetas estilo ASP y se pueden activar o desactivar desde el fichero de configuración php.ini Aunque para algunas personas las etiquetas cortas y etiquetas estilo ASP las encuentran más convenientes, son menos portables y generalmente no recomendadas.

Nota:

Observe también que si se está incrustando PHP con XML o XHTML necesitará usar las etiquetas <?php ?> para seguir los estándares.

Ejemplo #2 Etiquetas de apertura y de fin de bloque de PHP

1.  <?php echo 'si se quiere mostrar documentos XHTML o XML, debe hacerse así'?>

2.  <script language="php">
        
echo 'algunos editores (como FrontPage) no les gusta
              las instruciones de proceso'
;
    
</script>

3.  <? echo 'esta es la forma más simple, una instrución de procesado SGML'?>
    <?= expression ?> Esto es una forma corta para "<? echo expression ?>"

4.  <% echo 'Quizá use de forma opcional etiquetas de estilo ASP'; %>
    <%= $variable; # Esto es una forma corta para "<% echo . . ." %>

Las etiquetas vistas en los ejemplos uno y dos están siempre disponibles, el ejemplo uno es el más común y recomendado de los dos.

Las etiquetas cortas (ejemplo tres) están solo disponibles cuando se activan mediante la directiva short_open_tag en el fichero de configuración php.ini o si PHP se configuró con la opción --enable-short-tags .

Las etiquetas de estilo ASP (ejemplo cuatro) están solo disponibles cuando se activan mediante la directiva asp_tags en el fichero de configuración php.ini.

Nota:

El uso de etiquetas cortas debe ser evitado cuando se desarrollan aplicaciones o librerias que están pensadas para su redistribución, o extender en servidores PHP que no están bajo su control, porque quizá las etiquetas cortas no están soportadas en un servidor determinado. Por portabilidad, redistribución de código, asegúrese no usar etiquetas cortas.

Nota:

En PHP 5.2 y anteriores, no se permite que un fichero contenga únicamente la etiqueta de inicio de bloque <?php. En PHP 5.3 si se permite siempre que existan uno o más caracteres espacions en blanco después de la etiqueta de apertura.

Nota:

Desde PHP 5.4, la etiqueta abreviada de echo <?= siempre es reconocida y válida, sin tener en cuenta la configuración de short_open_tag.



Instrucción separador> <Etiquetas de PHP
[edit] Last updated: Fri, 25 May 2012
 
add a note add a note User Contributed Notes Salir de HTML
mike at clove dot com 30-Nov-2010 10:30
It's possible to write code to create php escapes which can be processed later by substituting \x3f for '?' - as in echo "<\x3fphp echo 'foo'; \x3f>";

This is useful for creating a template parser which later is rendered by PHP.
quickfur at quickfur dot ath dot cx 26-Jul-2010 02:40
When the documentation says that the PHP parser ignores everything outside the <?php ... ?> tags, it means literally EVERYTHING. Including things you normally wouldn't consider "valid", such as the following:

<html><body>
<p<?php if ($highlight): ?> class="highlight"<?php endif;?>>This is a paragraph.</p>
</body></html>

Notice how the PHP code is embedded in the middle of an HTML opening tag. The PHP parser doesn't care that it's in the middle of an opening tag, and doesn't require that it be closed. It also doesn't care that after the closing ?> tag is the end of the HTML opening tag. So, if $highlight is true, then the output will be:

<html><body>
<p class="highlight">This is a paragraph.</p>
</body></html>

Otherwise, it will be:

<html><body>
<p>This is a paragraph.</p>
</body></html>

Using this method, you can have HTML tags with optional attributes, depending on some PHP condition. Extremely flexible and useful!
snor_007 at hotmail dot com 01-Apr-2010 04:28
Playing around with different open and close tags I discovered you can actually mix different style open/close tags

some examples

<%
//your php code here
?>

or

<script language="php">
//php code here
%>
ravenswd at gmail dot com 01-Aug-2009 05:08
One aspect of PHP that you need to be careful of, is that ?> will drop you out of PHP code and into HTML even if it appears inside a // comment. (This does not apply to /* */ comments.) This can lead to unexpected results. For example, take this line:

<?php
  $file_contents 
= '<?php die(); ?>' . "\n";
?>

If you try to remove it by turning it into a comment, you get this:

<?php
//  $file_contents  = '<?php die(); ?>' . "\n";
?>

Which results in ' . "\n"; (and whatever is in the lines following it) to be output to your HTML page.

The cure is to either comment it out using /* */ tags, or re-write the line as:

<?php
  $file_contents 
= '<' . '?php die(); ?' . '>' . "\n";
?>
eksith at live dot com 01-Jul-2009 11:56
Even if it's pretty simple to insert echo lines to your PHP, I would storngly advise against it.

The safest way to output  HTML content which may have special chraracters is to remove the HTML from your core code.

Put them in heredocs instead.

See the heredoc documentation and comments for more examples.

If you can remove as much of the HTML as you can from the rest of the PHP code (in terms of printf and echo lines), please do.

Try to keep your core logic and presentation separate.

<?php
$html
=<<<HTML
<?xml version="1.0" encoding="UTF-8" ?>

... The rest of your HTML...

And a PHP
{$variable} here and an array {$arr['value']} there.

HTML; // End of heredoc

// Print this HTML
echo $html
?>
Richard Neill 03-Apr-2009 07:26
WARNING: there is a potentially *nasty* gotcha here. Consider the following:

<html><body><pre>
First line  <?/* Comment, inside PHP */?>
Second line
</pre></body></html>

If the comment is immediately followed by newline (and most editors will trim spaces at the ends of lines anyway), then you will NOT get what you expect.

Expect:
  First line
  Second Line

Actually get:
  First line  Second line 

Now, if you are relying on that newline, for example to terminate a line of Javascript, where the trailing semicolon is optional, watch out!
david dot jarry at gmail dot com 26-Mar-2009 03:40
Shorts tags and ASP tags are unportables and should be avoided.

<script /> tags are a waste of time and simply inefficient in some simple cases :
<body>
  <p style="color: <script language="php"> echo $text_color </script>;">
  (...) VERY long text (...)
  </p>
</body>
To render this example in a basic XHTML editor, you need to "echo()" all the content or break the XML rules.

The solution seems obvious to me : Why not add the shortcut "<?php= ?>" to be used within XML and XHTML documents ?
<?php='example1'?>
<?php=$example2?>
phpcoder at cyberpimp dot awmail dot org 09-Jan-2009 11:14
Some graphical HTML editors (and most web browsers) don't explicitly recognize the <?php ?> tags.  When opening a PHP file with a graphical HTML editor to design the page layout, chunks of PHP code can appear as literal text if the PHP code contains a greater-than symbol (>).

Example:

<html>
<body>
Unsafe-<?php
   
if (4>3) {
        echo
"PHP-";
    }
?>embedding
</body>
</html>

When executed, it should display this:

Unsafe-PHP-embedding

However, when opened with an HTML editor, the on-screen result might look like this:

Unsafe-3) { echo "PHP-"; } ?>embedding

...and further, the PHP code after the great-than operator (>) is at risk of being corrupted by the HTML editor's text formatting algorithms.

PHP code with greater-than symbols can be safely embedded into HTML by surrounding it with a pair of HTML-style comment delimiters + fake HTML end & start stags, as PHP-style comments.

Example:

<html>
<body>
Safe-<?php
/*><!--*/
   
if (4>3) {
        echo
"PHP-";
    }
/*--><?*/
?>embedding
</body>
</html>

When executed, it should display this:

Safe-PHP-embedding

And when opened with an HTML editor (or even opened directly with a web browser), it should display this:

Safe-embedding

An HTML editor will see the surrounded PHP code as an HTML comment, and (hopefully) leave it as-is.

Finally, any PHP code with a hard-coded string containing the HTML end-of-comment delimiter (-->) should be reconstructed to be syntactically identical, while avoiding the literal "-->" sequence in the PHP code.

For example, this:

<?php
/*><!--*/
   
$a = "-->";
/*--><?*/
?>

...can safely be changed to any of these:

<?php
/*><!--*/
   
$a = "\55->";
/*--><?*/
?>

<?php
/*><!--*/
   
$a = "--\76";
/*--><?*/
?>

<?php
/*><!--*/
   
$a = '--'.'>';
/*--><?*/
?>
admin at furutsuzeru dot net 02-Jan-2009 08:50
These methods are just messy. Short-opening tags and ASP-styled tags are not always enabled on servers. The <script language="php"></script> alternative is just out there. You should just use the traditional tag opening:

<?php?>

Coding islands, for example:

<?php
$me
'Pyornide';
?>
<?=$me;?> is happy.
<?php
$me
= strtoupper($me);
?>
<?=$me;?> is happier.

Lead to something along the lines of messy code. Writing your application like this can just prove to be more of an
inconvenience when it comes to maintenance.

If you have to deal chunks of HTML, then consider having a templating system do the job for you. It is a poor idea to rely on the coding islands method as a template system in any way, and for reasons listed above.

 
show source | credits | stats | sitemap | contact | advertising | mirror sites