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

search for in the

Séparation des instructions> <Balises PHP
[edit] Last updated: Fri, 17 May 2013

view this page in

Échappement depuis du HTML

Tout ce qui se trouve en dehors d'une paire de balises ouvrantes/fermantes est ignoré par l'analyseur PHP, ce qui permet d'avoir des fichiers PHP mixant les contenus. Ceci permet à PHP d'être contenu dans des documents HTML, pour créer par exemple des templates.

<p>Ceci sera ignoré par PHP et affiché au navigateur.</p>
<?php echo 'Alors que ceci sera analysé par PHP.'?>
<p>Ceci sera aussi ignoré par PHP et affiché au navigateur.</p>
Ceci fonctionne comme prévu parce que lorsque l'interpréteur PHP rencontre la balise fermante ?>, il commence simplement à afficher ce qu'il rencontre (mise à part s'il est immédiatement suivi d'une nouvelle ligne : voir l'instruction de séparation) jusqu'à ce qu'il rencontre une autre balise ouvrante même si PHP se trouve au milieu d'une instruction conditionnelle, au quel cas, l'interpréteur va déterminer la condition à prendre en compte avant de prendre une décision sur ce qui doit être afficher. Voir le prochain exemple.

Utilisation de structures avec des conditions

Exemple #1 Echappement avancé en utilisant des conditions

<?php if ($expression == true): ?>
  Ceci sera affiché si l'expression est vrai.
<?php else: ?>
  Sinon, ceci sera affiché.
<?php endif; ?>
Dans cet exemple, PHP va ignorer les blocs où la condition n'est pas remplie, même si ils sont en dehors des balises ouvrantes/fermantes de PHP. PHP va les ignorer suivant la condition vu que l'interpréteur PHP va passer les blocs contenant ce qui n'est pas remplie par la condition.

Pour afficher de gros blocs de texte, il est plus efficace de sortir du mode d'analyse de PHP plutôt que d'envoyer le texte via la fonction echo ou print.

Il y a quatre paires différentes de balises ouvrantes / fermantes qui peuvent être utilisées dans PHP. Deux de ces balises, <?php ?> et <script language="php"> </script>, sont toujours disponibles. Les deux autres sont les balises courtes et les balises du style ASP, et peuvent être activées ou désactivées depuis le fichier de configuration php.ini. Cependant, malgré le fait que des personnes trouvent les balises courtes et les balises du style ASP pratiques, elles sont moins portables et donc, généralement, non recommandées.

Note:

Notez également que si vous intégrez PHP dans des documents XML ou XHTML, vous devez utiliser les balises <?php ?> pour rester conforme aux standards.

Exemple #2 Balises d'ouvertures et de fermetures PHP

1.  <?php echo 'Si vous voulez réaliser des documents XHTML ou XML, faites comme ceci'?>

2.  <script language="php">
        
echo 'quelques éditeurs (comme FrontPage)
                 n\'aiment pas ce genre d\'instructions'
;
    
</script>

3.  <? echo 'ceci est le plus simple, une instruction SGML'?>
    <?= expression ?> Ceci est la version courte pour "<? echo expression ?>"

4.  <% echo 'Vous pouvez optionnellement utiliser les balises ASP-style'; %>
    <%= $variable; # Ceci est la version courte pour "<% echo . . ." %>

Bien que les balises vues dans les exemples un et deux sont toutes les deux disponibles, l'exemple un est le plus communément utilisé et le plus recommandé des deux.

Les balises courtes (troisième exemple) ne sont disponibles que s'elles ont été activées via la directive short_open_tag du fichier de configuration php.ini, ou si PHP a été configuré avec l'option --enable-short-tags .

Les balises du style ASP (quatrième exemple) sont uniquement disponibles lorsqu'elles sont activées via la directive asp_tags du fichier de configuration php.ini.

Note:

L'utilisation des balises courtes doit être bannie lors de développements d'applications ou de bibliothèques qui sont destinées à être redistribuées, ou déployées sur des serveurs qui ne sont pas sous votre contrôle, car les balises courtes peuvent ne pas être supportées sur le serveur cible. Pour réaliser du code portable, qui peut être redistribué, n'utilisez jamais les balises courtes.

Note:

En PHP 5.2 et antérieures, l'analyseur n'autorisait pas un tag ouvrant <?php comme seul élément d'une page. Ceci est permis à compter de la version 5.3 de PHP lorsqu'il y a un ou plusieurs espaces après la balise ouvrante.

Note:

Depuis PHP 5.4, le tag echo court <?= est toujours reconnu et valide, suivant la configuration de l'option short_open_tag.



Séparation des instructions> <Balises PHP
[edit] Last updated: Fri, 17 May 2013
 
add a note add a note User Contributed Notes Échappement depuis du HTML - [9 notes]
up
17
quickfur at quickfur dot ath dot cx
2 years ago
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!
up
8
snor_007 at hotmail dot com
3 years ago
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
%>
up
4
david dot jarry at gmail dot com
4 years ago
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?>
up
3
mike at clove dot com
2 years ago
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.
up
2
ravenswd at gmail dot com
3 years ago
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";
?>
up
0
admin at furutsuzeru dot net
4 years ago
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.
up
-2
Richard Neill
4 years ago
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!
up
-4
phpcoder at cyberpimp dot awmail dot org
4 years ago
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 = '--'.'>';
/*--><?*/
?>
up
-8
eksith at live dot com
3 years ago
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
?>

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