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

search for in the

命令の分離> <基本的な構文
Last updated: Fri, 13 Nov 2009

view this page in

HTML からの脱出

PHP はファイルを解析して開始タグと終了タグを探します。タグが 見つかると、PHP はコードの実行を開始したり終了したりします。 このような仕組みにより、PHP を他のあらゆる形式のドキュメント中に 埋め込むことができるのです。つまり、開始タグと終了タグで囲まれている 箇所以外のすべての部分は、PHP パーサに無視されます。 たいていの場合、PHP は HTML ドキュメントの中に埋め込まれます。 たとえば以下のようにです。

<p>この部分は無視されます。</p>
<?php echo '一方、この部分はパースされます。'?>
<p>この部分も無視されます。</p>

もっと複雑な構造を用いることもできます:

例1 高度なエスケープ処理

<?php
if ($expression) {
    
?>
    <strong>真です。</strong>
    <?php
} else {
    
?>
    <strong>偽です。</strong>
    <?php
}
?>

これは期待通りに動作します。なぜなら、PHP は ?> 終了タグを見つけると それ以降新たに開始タグを見つけるまでの内容を何でも出力するからです (終了タグの直後の改行は別です。 命令の分離 を参照ください)。 確かにこの例には少し無理があります。しかし、大量のテキストを出力する際に echo()print() を用いることを 考えると、このように一度 PHP のパースモードを抜けるほうが効率的です。

PHP で用いられるタグは 4 種類あります。 これらのうちの 2 つ、<?php ?> と <script language="php"> </script> は常に使用することができます。 残りの 2 つは短縮型のタグと ASP スタイルの タグで、これらは php.ini ファイルによって有効か無効かを切り替えられます。 中には短縮型のタグや ASP スタイルのタグを 便利に感じる人がいるかも知れませんが、長いタグに比べると移植性に欠けます。 また一般的には推奨されていません。

注意: さらに注意しなければならないことがあります。PHP コードを XML や XHTML に 埋め込む場合には、標準規格に従うために <?php ?> タグを使用する 必要があるでしょう。

例2 PHP の開始タグと終了タグ

1.  <?php echo 'XHTMLまたはXMLドキュメントを処理したい場合は、この方法が良いでしょう'?>

2.  <script language="php">
        
echo '(FrontPageのような) いくつかのエディタ は処理命令を好み
        ません'
;
    
</script>

3.  <? echo 'これは、SGML を処理する最もシンプルな方法です'?>
    <?= expression ?> This is a shortcut for "<? echo expression ?>"

4.  <% echo 'オプションでASP形式のタグを使用可能です'; %>
    <%= $variable; # これは、"<%echo .." のショートカットです。%>

例の 1. と 2. のタグは常に利用可能です。中でも 1. のタグは最も一般的で 推奨される方法です。

短縮型のタグ(例 3.)が有効なのは、php.ini 設定ファイルのディレクティブ short_open_tag が 有効になっている場合か PHP が --enable-short-tags オプションつきで configure されている場合のみです。

ASP 型のタグ(例 4.)が有効なのは、 php.ini 設定ファイルのディレクティブ asp_tags が有効になっている場合のみです。

注意: 再利用されるか、または、自分の制御下にないPHPサーバで運用される アプリケーションまたはライブラリを開発する場合、短縮型のタグの 使用は避けるべきです。これは、短縮型のタグがターゲットサーバー でサポートされていない可能性があるためです。 可搬性のある、再配布可能なコードでは、短縮型のタグを使用しない ようにしてください。



命令の分離> <基本的な構文
Last updated: Fri, 13 Nov 2009
 
add a note add a note User Contributed Notes
HTML からの脱出
ravenswd at gmail dot com
02-Aug-2009 12: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
02-Jul-2009 06: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
04-Apr-2009 03: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 11: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-Jan-2009 07: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 04: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.

命令の分離> <基本的な構文
Last updated: Fri, 13 Nov 2009
 
 
show source | credits | sitemap | contact | advertising | mirror sites