PHP Doku:: Den HTML-Bereich der Datei verlassen - language.basic-syntax.phpmode.html

Verlauf / Chronik / History: (1) anzeigen

Sie sind hier:
Doku-StartseitePHP-HandbuchSprachreferenzGrundlagen der SyntaxDen HTML-Bereich der Datei verlassen

Ein Service von Reinhard Neidl - Webprogrammierung.

Grundlagen der Syntax

<<Grundlagen der Syntax

Abgrenzung von Anweisungen>>

Den HTML-Bereich der Datei verlassen

Wenn PHP eine Datei parst, sucht es nach öffnenden und schließenden Tags, die PHP anweisen, den dazwischen befindlichen Code zu interpretieren. Das Parsen auf diese Art erlaubt Ihnen, PHP in allen möglichen Arten von unterschiedlichen Dokumenten einzubinden, da alles außerhalb des Paars aus öffnendem und schließendem Tag vom Parser ignoriert wird. In den meisten Fällen werden Sie wie im folgenden Beispiel PHP in HTML-Dokumente eingebettet finden.

<p>Das hier wird ignoriert werden.</p>
<?php echo 'Wohingegen das hier geparst werden wird.'?>
<p>Dies wird ebenfalls ignoriert.</p>

Sie können aber auch komplexere Strukturen verwenden:

Beispiel #1 Fortgeschrittenes Erweitern

<?php
if ($ausdruck) {
    
?>
    <strong>Dies ist wahr.</strong>
    <?php
} else {
    
?>
    <strong>Dies ist falsch.</strong>
    <?php
}
?>
Dies arbeitet wie erwartet, da PHP, wenn es auf ein schließendes >?-Tag trifft, einfach beginnt, alles folgende auszugeben, bis es wieder auf einen öffnenden Tag stößt (mit Ausnahme eines direkt folgenden Newline-Zeichens - siehe auch Abschnitt Abgrenzung von Anweisungen). Das hier angegebene Beispiel ist natürlich nur ausgedacht, aber für die Ausgabe von großen Textblöcken ist der Ausstieg aus dem Parse-Modus generell effizienter, als den gesamten Text durch echo() oder print() zu jagen.

Es gibt vier unterschiedliche Paare öffnender und schließender Tags, die in PHP verwendet werden können. Zwei davon, <?php ?> und <script language="php"> </script>, sind immer verfügbar. Die anderen beiden sind Short-Tags und ASP-Tags, die über das php.ini-Konfigurationsfile ein- und ausgeschaltet werden können. Das bedeutet, wenn einige Leute Short-Tags und ASP-Tags bequem finden, sind die daraus resultierenden Skripte nicht überall einsetzbar, so dass diese Tags grundsätzlich nicht empfehlenswert sind.

Hinweis:

Beachten Sie auch, dass Sie, wenn Sie PHP in XML oder XHTML einbinden wollen, die <?php ?>-Tags verwenden müssen, um keine Parserfehler aufgrund vermischter Standards zu provozieren.

Beispiel #2 Die öffnenden und schließenden Tags von PHP

1.  <?php echo
      
'wenn Sie XHTML- oder XML-Dokumente ausliefern wollen, machen Sie es so'?>

2.  <script language="php">
        
echo 'manche Editoren(wie FrontPage) moegen
              keine Verarbeitungsanweisungen'
;
    
</script>

3.  <? echo 'das ist das Einfachste, eine SGML-Verarbeitungsanweisung'?>

4.  <% echo 'Optional koennen Sie auch Tags im ASP-Stil verwenden'; %>
    <%= $variable; # Das ist ein Abkuerzung fuer "<% echo . . ." %>

Während die Tags in Beispiel eins und zwei jederzeit verfügbar sind, ist Beispiel eins das meist verwendete und grundsätzlich empfohlene von beiden.

Short-Tags (Beispiel drei) sind nur verfügbar, wenn sie via short_open_tag-Direktive im php.ini-Konfigurationsfile eingeschaltet wurden, oder wenn PHP mit --enable-short-tags konfiguriert wurde.

ASP-Tags (Beispiel vier) sind nur verfügbar, wenn sie mittels der asp_tags-Direktive im php.ini Konfigurationsfile eingeschaltet wurden.

Hinweis:

Die Verwendung der Short-Tags sollten Sie vermeiden, wenn Sie Applikationen oder Bibliotheken entwickeln, die für die Weitergabe oder den Einsatz auf nicht Ihrer Kontrolle unterstehenden PHP-Servern bestimmt sind, da es sein kann, dass Short-Tags auf dem Zielsystem nicht unterstützt werden. Um portablen, weiterverteilbaren Code zu haben, verwenden Sie keine Short-Tags.


9 BenutzerBeiträge:
- Beiträge aktualisieren...
mike at clove dot com
30.11.2010 19: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.07.2010 23: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
2.04.2010 2: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
2.08.2009 2: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
2.07.2009 8: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
4.04.2009 5: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.03.2009 12: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
10.01.2009 8: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
2.01.2009 17: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.



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",...)