|
|
 |
CapÃtulo 10. Sintaxis básica
Para interpretar un archivo, php sÃmplemente interpreta el texto
del archivo hasta que encuentra uno de los carácteres especiales
que delimitan el inicio de código PHP. El intérprete ejecuta
entonces todo el código que encuentra, hasta que encuentra una etiqueta
de fin de código, que le dice al intérprete que siga ignorando el código
siguiente. Este mecanismo permite embeber código PHP dentro de HTML: todo lo que está
fuera de las etiquetas PHP se deja tal como está, mientras que el resto se interpreta
como código.
Hay cuatro conjuntos de etiquetas que pueden ser usadas para denotar
bloques de código PHP. De estas cuatro, sólo 2 (<?php. . .?> y
<script language="php">. . .</script>) están siempre disponibles;
el resto pueden ser configuradas en el fichero de php.ini para ser
o no aceptadas por el intérprete. Mientras que el formato corto de etiquetas (short-form tags) y
el estilo ASP (ASP-style tags) pueden ser convenientes, no son portables
como la versión de formato largo de etiquetas. Además, si se pretende
embeber código PHP en XML o XHTML, será obligatorio el uso del formato
<?php. . .?> para la compatibilidad con XML.
Las etiquetas soportadas por PHP son:
Ejemplo 10-1. Formas de escapar de HTML |
1. <?php echo("si quieres servir documentos XHTML o XML, haz como aquí\n"); ?>
2. <? echo ("esta es la más simple, una instrucción de procesado SGML \n"); ?>
<?= expression ?> Esto es una abreviatura de "<? echo expression ?>"
3. <script language="php">
echo ("muchos editores (como FrontPage) no
aceptan instrucciones de procesado");
</script>
4. <% echo ("Opcionalmente, puedes usar las etiquetas ASP"); %>
<%= $variable; # Esto es una abreviatura de "<% echo . . ." %>
|
|
El método primero, <?php. . .?>, es el más conveniente, ya que
permite el uso de PHP en código XML como XHTML.
El método segundo no siempre está disponible. El formato corto
de etiquetas está disponible con la función short_tags()
(sólo PHP 3), activando el parámetro del fichero de configuración de PHP
short_open_tag, o compilando
PHP con la opción --enable-short-tags del comando configure.
Aunque esté activa por defecto en php.ini-dist, se desaconseja
el uso del formato de etiquetas corto.
El método cuarto sólo está disponible si se han activado las
etiquetas ASP en el fichero de configuración: asp_tags.
Nota: El soporte de etiquetas ASP se añadió en la versión 3.0.4.
Nota:
No se debe usar el formato corto de etiquetas cuando se
desarrollen aplicaciones o bibliotecas con intención de
redistribuirlas, o cuando se desarrolle para servidores que no
están bajo nuestro control, porque puede ser que el
formato corto de etiquetas no esté soportado en el
servidor. Para generar código portable y
redistribuÃble, asegúrate de no usar el formato
corto de etiquetas.
La etiqueta de fin de bloque incluirá tras ella la siguiente
lÃnea si hay alguna presente. Además, la etiqueta de fin de bloque
lleva implÃcito el punto y coma; no necesitas por lo tanto añadir
el punto y coma final de la última lÃnea del bloque PHP.
PHP permite estructurar bloques como:
Ejemplo 10-2. Métodos avanzados de escape |
<?php
if ($expression) {
?>
<strong>This is true.</strong>
<?php
} else {
?>
<strong>This is false.</strong>
<?php
}
?>
|
|
Este ejemplo realiza lo esperado, ya que cuando PHP encuentra las etiquetas
?> de fin de bloque, empieza a escribir lo que encuentra tal cual hasta que
encuentra otra etiqueta de inicio de bloque. El ejemplo anterior es, por supuesto,
inventado. Para escribir bloques grandes de texto generamente es más eficiente
separalos del código PHP que enviar todo el texto mediante las funciones
echo(), print() o similares.
add a note
User Contributed Notes
Sintaxis básica
alfridus
23-Jul-2006 04:53
Only this work:
<?php
$xml = '<?xml version="1.0" encoding="UTF-8" standalone="no"?>';
echo $xml;
?>
with space after '<?php' and before ' ?>', no spacing between
'<?xml' and a semicolon after '"no"?>';'.
php at pixo dot sk
04-Apr-2006 04:58
just for conclusion:
<?php echo('<?xml version="1.0" ?'.'>'); ?>
is the right choice :)
brettz9 at yahoo dot com
02-Apr-2006 08:04
I've essentially tried to synthesize this
discussion at
http://en.wikibooks.org/wiki/Programming:
Complete_PHP/Escaping_from_HTML
One point not brought up yet...
The HEREDOC problem with some text editors
may be fixable in at least some text editors
by adding a comment with a quotation mark
as such afterwards (albeit necessarily on a
new line):
<?php
$version = "1.0";
print <<<HERE
<?xml version="
HERE;
print $version."\"?>";
?>
Christoph
16-Jan-2006 05:08
Here's an inspiration on how to quickly fix all scripts relying on short_open_tag being enabled:
find -name '*.php' | xargs perl -pi -e 's/<\?= ?(.*?) ?\?>/<?php echo($1); ?>/g'
find -name '*.php' | xargs perl -pi -e 's/<\?/<?php/g'
find -name '*.php' | xargs perl -pi -e 's/<?phpphp/<?php/g'
Michael Newton (http://mike.eire.ca/)
12-Dec-2005 03:17
The XML declaration does not need to be handled specially.
You should output it via an echo statement, in case your code is ever used on a server that is (poorly) configured to use short open tags.
But there's no need to treat the ?> at the end of the string specially. That's because it's in a string. The only thing PHP ever looks for in a string is \ or $ (the latter only in double-quoted strings.)
I have never had need for the following, as some have suggested below:
<?php
$xml=rawurldecode('%3C%3Fxml%20version%3D%221.0%22%3F%3E');
echo($xml);
?>
<?php echo '<?xml version="1.0" ?'.'>' ?>
<?php echo "<?xml version=\"1.0\"\x3F>" ?>
php [AT] jsomers [DOT] be
23-Sep-2005 12:37
PEAR states:
Always use <?php ?> to delimit PHP code, not the <? ?> shorthand. This is required for PEAR compliance and is also the most portable way to include PHP code on differing operating systems and setups.
It are these small things that enhance readability in group projects, or libraries.
pablo [] littleQ.net
24-Jul-2005 02:06
Just another more "feature" of IE...
Content-Disposition: attachment; filename=\"__FILE__\";
__FILE__ can't have spaces or :
Regards
01karlo at gmail dot com
25-Jun-2005 08:44
Or, use the following:
<?php
$xml=rawurldecode('%3C%3Fxml%20version%3D%221.0%22%3F%3E');
echo($xml);
?>
What is does it the value of the variable $xml is the RAW Url Encoded version of the XML thing.
Then it decodes it and echo it to the visitor.
p o r g e s at the gmail dot com server
01-Apr-2005 08:02
mike at skew dot org, I believe the differentiation is that "x"-"m"-"l" as a PI target is explicitly excluded from the definition of processing instructions.
Lachlan Hunt
28-Mar-2005 09:06
The person that suggested the use of this meta element above is wrong:
<meta http-equiv="Content-Type" content="application/xml+xhtml; charset=UTF-8" />
That meta element and the XML declaration serve completely different purposes, and that meta element should not be used. Such information should be set using the HTTP Content-Type header (see the header() function).
Any XHTML page that just uses that meta element without proper HTTP Content-Type header, will be processed as text/html by browsers regardless, and when the HTTP headers do serve as application/xhtml+xml (or other XML MIME type), that charset parameter in the meta element will be ignored.
mike at skew dot org
21-Oct-2004 04:53
mart3862 mentions "XML processing instructions" and quotes their syntax from the spec, but is mistaken in using
<?xml version="1.0" ...?>
as an example. This little bit of markup that appears at the beginning of an XML file is in fact not a processing instruction at all; it is an "XML declaration" -- or, if it appears in an entity other than the main document, a "text declaration". All three constructs are formatted slightly differently, although they all do begin and end with the same.
The difference between a processing instruction, an XML declaration, or a text declaration is more than just a matter of subtle differences in syntax, though. A processing instruction embodies exactly two opaque, author-defined pieces of information (a 'target' and an 'instruction') that are considered to be part of the document's logical structure and that are thus made available to an application by the XML parser. An XML or text declaration, on the other hand, contains one to three specific pieces of information (version, encoding, standalone status), each with a well-defined meaning. This info provides cues to the parser to help it know how to read the file; it is not considered part of the document's logical structure and is not made available to the application.
stooges_cubed at racerx dot net
20-Oct-2004 01:13
In the note above about escaping XML/PHP style <?xml tags, the following code was used:
<?php echo <<<EOD
<?xml version="1.0"?>
...all sorts of XML goes here...
Nothing will affect the output of this code until:
EOD;
?>
EOD is just an example stop/start name.
This works too:
<?php $myOutput = <<<MYHTMLSAFEOUTPUT
<?xml version="1.0"?>
<html>
<title>PHP Example</title>
<body>
<p>...all sorts goes here...</p>
</body>
</html>
MYHTMLSAFEOUTPUT;
echo $myOutput;
?>
Only disadvantage of using this is that all the code highlighting programs I've seen never get it right, making your code look eronous in the majority of viewers.
Another alternative is to keep the XML / HTML in a separate include file and read in when needed. I don't know how efficient/inefficient this is for (idiots like yourselves) small amounts of text.
xmlheader.txt:
<?xml version="1.0"?>
mypage.php:
<?php
include("xmlheader.txt");
?>
crtrue at coastal dot edu
30-Apr-2004 11:02
Although you can use the above methods to pass a document off as a valid for the W3C parser, a simpler-and-perfectly-legal method of doing so is to simple declare the document type in a meta tag. Something along these lines (mind the values in 'content' - I haven't personally used the Content-Type method in awhile):
<meta http-equiv="Content-Type" content="application/xml+xhtml; charset=UTF-8" />
Of course if you're using just XML, and don't use such functions, then the above methods will work just as fine.
mart3862 at yahoo dot com dot au
18-Apr-2004 09:29
Now the ultimate truth on how you should output xml processing instructions:
There have been several posts suggesting ways to include the text <?xml version="1.0" encoding="utf-8"?> in your output when short_tags is turned on, but only the following should be used:
<?php echo '<?xml version="1.0" ?'.'>' ?>
or
<?php echo "<?xml version=\"1.0\"\x3F>" ?>
Using one of these methods, and not making use of short tags, means your source code will also be a valid XML document, which allows you to do many things with it such as validation, XSLT translations, etc, as well as allowing your text editor to parse your code for syntax colouring. Every PHP tag will simply be interpreted as an XML processing instruction (commonly referred to as PI).
The reason why all the other suggested methods are not advisable is because they contain the characters ?> inside the PHP tag, which the XML parser will interpret as the end of the processing instruction.
A processing instruction is defined in XML as:
PI ::= '<?' PITarget (S (Char* - (Char* '?>' Char*)))? '?>'
In other words, it explicitly forbids the characters ?> to occur together within a processing instruction, unless they are delimiting the end of the tag. It also requires a PITarget (an identifier starting with a letter) immediately after the initial start delimiter, which means that all short tag formats are also invalid XML.
Following these guidelines will result in code that is portable to servers with any configuration and allow you perform many useful tasks on your XML or XHTML source documents. Even if you do not intend to validate or translate your source documents, and you can ignore some incorrect syntax colouring in your text editor, it is still best to get into good habits early.
Anon
21-Feb-2004 06:05
Yet another way of adding the XML processing instruction is to use:
<?php echo '<?xml version="1.0" ?'.'>' ?>
Because the ? and > are separated, the parser will not terminate before it is supposed to.
As a side note, the W3C's parser seems to recognise this method (assuming it even checks for the PI).
TarquinWJ
06-Feb-2004 06:54
Not spotted any messages like this one - delete it if there was one.
My hosting service allows <? and ?>, but I like to use valid XHTML, so I came up with this simple solution:
It is possible to use the short tags <? ?> with XHTML or XML documents. The only problem is that X(HT)ML requires a declaration using <? and ?>
<?xml version="1.0" encoding="UTF-8"?>
To avoid the problem, simply replace <? with <<? ?>?
and ?> with ?<? ?>>
<<? ?>?xml version="1.0" encoding="UTF-8"?<? ?>>
This inserts a blank piece of PHP in between the < and ?, and when parsed will output the regular tag
<?xml version="1.0" encoding="UTF-8"?>
mwild at iee dot NO_SP_AM dot org
19-Dec-2003 05:12
The text between <script> and </script> in XHTML is PCDATA, so < and & characters in it should be interpreted as markup. This is a bit limiting for PHP, which is often used to output tags, though you can of course use < and & instead. To avoid that, which makes your code look peculiar and is easy to forget to do, you can mark the PHP as CDATA, eg :
<script language="PHP">
echo('Today is <b>'.date('l F jS').'</b>');
</script>
If you don't do this, and your code contains < or &, it should be rejected by an XHTML validator.
johnbeech at (not saying) mkv25 dot net
07-Dec-2003 04:42
In the note above about escaping XML/PHP style <?xml tags, the following code was used:
<?php echo <<<EOD
<?xml version="1.0"?>
...all sorts of XML goes here...
Nothing will affect the output of this code until:
EOD;
?>
EOD is just an example stop/start name.
This works too:
<?php // Html safe containers
$myOutput = <<<MYHTMLSAFEOUTPUT
<?xml version="1.0"?>
<html>
<title>PHP Example</title>
<body>
<p>...all sorts goes here...</p>
</body>
</html>
MYHTMLSAFEOUTPUT;
echo $myOutput;
?>
Only disadvantage of using this is that all the code highlighting programs I've seen never get it right, making your code look eronous in the majority of viewers.
Another alternative is to keep the XML / HTML in a separate include file and read in when needed. I don't know how efficient/inefficient this is for small amounts of text.
xmlheader.txt:
<?xml version="1.0"?>
mypage.php:
<?php
include("xmlheader.txt");
?>
dave at [nospam] dot netready dot biz
18-Mar-2002 04:21
A little "feature" of PHP I've discovered is that the <?PHP token requires a space after it whereas after the <? and <% tokens a space is optional.
The error message you get if you miss the space is not too helpful so be warned!
(These examples only give a warning with error_reporting(E_ALL) )
<?PHP?> fails...
<??> works...
mrtidy at mail dot com
12-Dec-2001 12:36
[Ed Note:
This is because of short_tags, <?xml turns php parsing on, because of the <?.
--irc-html@php.net]
I am moving my site to XHTML and I ran into trouble with the <?xml ?> interfering with the <?php ?> method of escaping for HTML. A quick check of the mailing list confirmed that the current preferred method to cleanly output the <?xml ?> line is to echo it:<br>
<?php echo("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"); ?>
| |
|
| Chiste de... Parejas | | Solteros o casados | - ¿Quiénes viven más los solteros o los casados?
- Igual, pero a los casados se les hace más largo el tiempo. | | Chistes en tu mail | | ©ContenidosGratis |
| Inicio | Acción | Estrategia | Palabras | Puzzles | Solitarios | Foro Trucos |  | Cake Mania Jugadores: 6835 Categoría del juego: Acción Objetivo del juego: Ayuda a Jill a recuperar la pastelería de su abuela llevando su propia pastelería; consigue clientes y gana dinero. |
|  | Rainbow Web Jugadores: 2199 Categoría del juego: Puzzles Objetivo del juego: Rompe un pegajoso hechizo y salva un reino de fantasía en Rainbow Web. Tendrás toneladas de diversión mientras juegas a este mágico desafío para la mente. |
|  | Mahjongg Fortuna Jugadores: 12462 Categoría del juego: Solitarios Objetivo del juego: Velocidad y habilidad mental son las armas más importantes en esta versión de un antiguo juego asiático. Despeja el tablero lo antes posible haciendo clic en las fichas iguales y gánate la fama eterna de la puntuación más alta. |
|  | Chainz 2 Jugadores: 6955 Categoría del juego: Puzzles Objetivo del juego: Entra en el mundo de las combinaciones con Chainz 2: Relinked, emocionante secuela del exitazo del año pasado, Chainz. Gira eslabones y crea combinaciones de 3 ó más. |
|  | Delicious Jugadores: 4405 Categoría del juego: Acción Objetivo del juego: ¿Eres un as de la multitarea? ¿Quieres que tus clientes estén contentos? ¡Pues Delicious es tu juego! Sacia el apetito de los clientes y tenlos contentos; ¡no te arriesgues! |
|  | Bookworm Jugadores: 4568 Categoría del juego: Palabras Objetivo del juego: Junta las letras para formar palabras. ¡Las palabras más largas valen más puntos! |
|  | Zuma Jugadores: 4976 Categoría del juego: Acción Objetivo del juego: Controla el ídolo de la rana de piedra de los antiguos Zuma en este intrigante enigma de acción. ¡Dispara bolas para formar conjuntos de tres, pero si dejas que lleguen a la calavera dorada morirás! |
|  | Jewel of Atlantis Jugadores: 3798 Categoría del juego: Puzzles Objetivo del juego: Descubre la ciudad hundida de la Atlántida y busca valiosos tesoros. Viaja más allá de las profundidades del mar y vive trepidantes aventuras en Jewel of Atlantis. |
|  | Jewel Quest Jugadores: 3727 Categoría del juego: Puzzles Objetivo del juego: Convierte la arena de la antigua selva en oro tan rápido como puedas juntando grupos de 3 elementos. ¡Los grupos más grandes valen más puntos! |
|  | Bejeweled 2 Jugadores: 3659 Categoría del juego: Puzzles Objetivo del juego: Con cuatro modos de juego únicos y fascinantes, nuevas piezas de juego explosivas e imponentes fondos planetarios, Bejeweled 2 es mucho más adictivo que nunca. |
|
|