PHP: 基本的な構文 - Manual
PHP  
downloads | documentation | faq | getting help | mailing lists | | php.net sites | links | my php.net 
search for in the  
<言語リファレンス命令の分離>
view the version of this page
Last updated: Tue, 21 Dec 2004

第 10章基本的な構文

HTML からの脱出

PHPはファイルからPHPコードの開始を示す特別なタグを見つけるまでは 単純にその内容を出力します。PHPコードの開始を示すタグが見つかると PHPはコードの終了を示すタグとの間にあるコードを実行します。この メカニズムによりPHPコードをHTMLの中に埋め込むことが出来るのです。 つまり、PHPタグの中にある文字列はPHPコードとして解釈されますが、 外にある文字列(つまり普通のHTML)はあくまで単純に出力されるだけ ということです。

PHPコードのブロックであることを宣言するタグは4種類あります。 これらのうちの2つ((<?php. . .?>と<script language="php"> . . .</script>)は常に使用することが出来ます。その他の タグはphp.ini設定ファイルでonまたはoffに するとが出来ます。短縮型のタグ(<?. . .?>)とASP形式の タグは便利なのですが、長いタグに比べると移植性に欠けます。 また、PHPコードをXMLやXHTMLに埋め込もうとする場合にはXMLの 規格に従うために<?php. . .?>形式を使用する必要があるでしょう。

PHPでサポートされるタグは以下のとおりです:

例 10-1. HTMLからの脱出法

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

2.  <? echo ("この方法は最も簡単で、SGMLの処理命令です\n"); ?>
    <?= expression ?> は "<? echo expression ?>"のショートカットです。
  
3.  <script language="php">
      
echo ("(FrontPageのような) いくつかのエディタ は処理命令を好み
       ません"
);
  
</script>

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

最初の方法が推奨されます。なぜなら、 XHTMLのようなXMLに適応したコードでPHPを使用できるからです。

2番目の方法は、短縮型のタグが有効な場合にのみ利用可能です。 短縮型のタグは、short_tags() 関数を使用するか (PHP 3のみ)、 PHPの設定ファイルに short_open_tagを設定する か--enable-short-tags オプションを configure に 指定して PHP をコンパイルすることにより、有効にできます。 php.ini-distでは、デフォルトでこのオプションは有効となっていますが、 短縮形のタグの使用は推奨されません。

4番目の方法は、ASP型式のタグが asp_tags の設定により有効となっ ている場合にのみ使用可能です。

注意: ASP 型のタグのサポートは、3.0.4で追加されました。

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

ブロックの終了タグは、直後に改行がある場合、それを含んだものになります。 また、終了タグには自動的にセミコロンが含まれていると認識されます。 従ってPHPコードの最終行にはセミコロンを記述する必要はありません。 ファイル終端におけるPHPブロックの終了タグはオプション(任意)です。

PHP は、次のような構造を使用可能です。

例 10-2. 高度なエスケープ処理

<?php
if ($expression) {
  
?>
    <strong>This is true.</strong>
   <?php
} else {
  
?>
    <strong>This is false.</strong>
   <?php
}
?>
このコードは期待通りに動作します。これは、PHPが?> および <?phpの中のテキストをecho()命令として処理す るためです。この例はもちろん不自然なものですがPHPモードを抜ける ことでテキストを出力させる方法は、それらをecho()print()等を使って出力させるより便利です。



add a note add a note User Contributed Notes
基本的な構文
mike at skew dot org
21-Oct-2004 11: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 08:13
In the note above about escaping XML/PHP style <?xml tags, the following code was used:

<?
php  // Html safe containers

  
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 (idiots like yourselves) small amounts of text.

xmlheader.txt:
<?xml version="1.0"?>

mypage.php:
<?php
 
include("xmlheader.txt");
?>
crtrue at coastal dot edu
01-May-2004 06: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 04: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.
george at whiffen dot net
26-Feb-2004 03:12
Tip: New lines immediately following a close tag, (?>,</script>) are suppressed in the output. 

For example:

Contact:-
Name:<?= $myname?>
Telephone: <?= $myphone?>

will typically produce:

Contact:-
Name: My NameTelephone: My Phone

To get the new line back, just add anything after the close tag and before the new line.  A single space character works fine.
Anon
22-Feb-2004 02: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 02: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 01: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 &lt; and &amp; 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">
//<![CDATA[
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
08-Dec-2003 12:42
In the note above about escaping XML/PHP style <?xml tags, the following code was used:

<?
php  // Html safe containers

  
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");
?>
de \ kibo \ niels
19-Dec-2002 02:19
A follow-up to the first posting on this page: If you're writing PHP code on a non-UNIX system like MacOS (and even on a UNIX system like Mac OS X!), be very careful about line breaks.

Although this was apparently fixed in 4.0.5, I got the weirdest errors while testing PHP scripts that I wrote in BBEdit (6.5) on MacOS X (10.2, running Apache 1.3.27 with PHP 4.1.2).

The Mac-style line breaks (\r) that BBEdit usually produces by default confuse the PHP parser, and it will report the strangest parse errors. (I even got errors in lines of code that were commented out! This drove me nuts for days).

Your documents have to use UNIX-style linebreaks (\n) to prevent these errors. It's advisable to configure BBEdit to produce UNIX line breaks by default in every new document (preferences!).

This problem possibly also occurs with DOS/Win systems whose linebreaks are \r\n.
dave at [nospam] dot netready dot biz
18-Mar-2002 12: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/*<Some HTML>*/?> fails...
<?/*<Some HTML>*/?> works...
mrtidy at mail dot com
12-Dec-2001 08: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"); ?>

<言語リファレンス命令の分離>
 Last updated: Tue, 21 Dec 2004
show source | credits | sitemap | contact | advertising | mirror sites 
Copyright © 2001-2005 The PHP Group
All rights reserved.
This unofficial mirror is operated at: /
Last updated: Mon Mar 14 08:13:06 2005 Local time zone must be set--see zic manual page