@evanplaice at aol dot com: The <script language="php"> tag won't be read by browsers; it will be parsed by PHP just like <?php and ?> are.
기본 문법
Table of Contents
HTML에서 벗어나기
PHP가 파일을 해석할때 PHP코드로 해석하라고 하는 특별한 코드와 만나지 않는다면 단순히 그 파일의 텍스트를 넘겨줄 뿐이다. 해석기(parser)는 PHP 닫기 태그가 있는곳까지 발견된 코드 모두를 수행한다. PHP 닫기 태그 를 만나면 다시 텍스트를 그냥 넘겨주기 시작하는것이다. 이런 메카니즘은 HTML안에 PHP코드를 내장시킬수 있게 해준다: PHP 태그 밖의 모든것은 완전히 단독으로 존재하는것이고, 반면에 PHP 태그 안쪽은 코드로서 해석이 된다.
PHP 코드 블록은 네가지의 태그형태로 표시할수 있다. 이 중에서 두가지 (<?php. . .?> 과 <script language="php">. . .</script>)는 항상 유효한 형태이다. 반면에 다른 형태는 php.ini 설정 파일에서 켜거나 끌 수 있다. 짧은형(short-form)태그와 ASP스타일(ASP-style) 태그는 편하겠지만, 긴 형태 태그만큼 이식성이 뛰어나진 못하다. XML이나 XHTML안에 PHP코드를 내장시키려면 XML과 호환될수 있도록 <?php. . .?>형을 써야한다.
PHP가 지원하는 태그 형태:
Example#1 HTML에서 벗어나기
1. <?php echo("XHTML나 XML 문서와 호환시키려면, 이렇게 쓰세요\n"); ?>
2. <? echo ("이런 형태가 제일간단하다. SGML 처리명령\n"); ?>
<?= expression ?>는 "<? echo expression ?>"을 간단히 쓴 태그형
3. <script language="php">
echo ("어떤 에디터 (프론트페이지같은)는
처리 명령을 좋아하지 않는다");
</script>
4. <% echo ("ASP스타일 태그를 쓸수도 있다"); %>
<%= $variable; # 이것은 "<% echo . . ." %>을 간단히 쓴 태그형
첫번째 방법 <?php. . .?>을 쓰는것이 가장 좋다. 이런 형태는 XHTML과 같은 XML호환 코드안에 PHP를 쓸수 있게 해주기때문이다.
두번째 방법은 항상 유효하지 않다. 이 짧은 형은 활성화시켰을때만 유효하다. short_tags() 함수 (PHP 3에서만)로, PHP 설정 파일 안의 short_open_tag 설정 값을 활성화시키거나, configure명령 시에 --enable-short-tags옵션을 줘서 PHP를 컴파일함으로써 가용하게 할수있다.
네번째 방법은 asp_tags설정값을 활성화시킴으로써 ASP 스타일 태그형태를 쓸수 있을때만 유효하다.
Note: 3.0.4부터 ASP 스타일 태그에 대한 지원이 추가되었다
Note: 프로그램이나 재사용을 위한 라이브러리를 개발할때, 또는 통제밖의 PHP서버에 배치시킬때는 짧은 형 태그를 쓰는것은 피해야 한다. 왜냐하면 짧은 형 태그는 목표하는 서버에서 지원되지 않을수도 있기 때문이다. 이식성을 위해서, 재사용 코드는 짧은 형 태그로 쓰지 않도록 한다.
블록의 닫기 태그가 하나만 존재한다면 그 뒤에 바로 새줄(newline)이 포함될것이다. 또, 닫기 태그는 자동적으로 세미콜른(;)의 역할도 수행한다. 따라서 PHP블록의 마지막 줄은 세미콜른 으로 끝낼 필요가 없다.
PHP는 다음과 같은 구조도 허용이 된다:
Example#2 향상된 회피(escaping)
<?php
if ($expression) {
?>
<strong>이것은 참이다.</strong>
<?php
} else {
?>
<strong>이것은 거짓이다.</strong>
<?php
}
?>
기본 문법
05-Mar-2008 09:21
30-Dec-2007 03:33
Correction for Example 2-2
The <script> "language" attribute has been deprecated
See:
http://www.w3.org/TR/REC-html40/interact/scripts.html#h-18.2.1
This should be noted in the example to update to the current standards.
28-Dec-2007 07:36
you also can use this kind of syntax:
<?php if( condition ): ?>
<?php else: ?>
<?php endif; ?>
15-Jul-2007 01:08
"This works as expected, because when PHP hits the ?> closing tags, it simply starts outputting whatever it finds"
This is worded very confusingly so if you think you know what's going on just ignore this (I knew how this had to work from ruby but this comment made me think I was confused). To be clear the documentation is NOT saying that whenever the PHP *parser* hits the closing tag it starts outputting whatever if finds. What they mean is that ?> acts just like a php instruction that outputs whatever text it finds until it sees a <?php
03-May-2007 03:22
Jascam: Try to find more resourceful information to make your point. Your lack of ability to understand more complex concepts is not enough to diminish such a popular language as PHP. Note also that php is not replacing html but complementing it.
17-Apr-2007 08:45
As rosswilliams mentioned; The example breaking in and out of the PHP tags doesn't "work as expected". The manual and some comments mention that PHP "simply starts outputting whatever it finds..." any time a closing tag is encountered. It would make sense to say instead - "...unless PHP is in the middle of a conditional statement; in which case it will only output the relevant block of HTML."
Some have said that using the 'echo' command is cleaner and more efficient. However, as the manual points out, the method of breaking out of PHP is more efficient when dealing with large sections of HTML. Because there is less work for the parser.
04-Mar-2007 05:19
Regarding the comment by rosswilliams at advocacytechnologies dot org:
Your suspicion is correct. The following all behave exactly the same:
<?php
// output the answer by escaping
if ($true_or_false) {
?>
<p>The value of $true_or_false is true.</p>
<?php
} else {
?>
<p>The value of $true_or_false is false.</p>
<?php
}
// use echo to do the same thing - more effecient and easier to read in my opinion
if ($true_or_false) {
echo '<p>The value of $true_or_false is true.</p>';
} else {
echo '<p>The value of $true_or_false is false.</p>';
}
// use ? : operators on entire string
echo ($true_or_false) ? '<p>The value of $true_or_false is true.</p>' : '<p>The value of $true_or_false is false.</p>';
// use ? : operators only on the pertinent bit, to save space
echo '<p>The value of $true_or_false is ' . (($true_or_false) ? 'true' : 'false') . '.</p>';
?>
29-Dec-2006 11:14
"This works as expected, because when PHP hits the ?> closing tags, it simply starts outputting whatever it finds until it hits another opening tag."
I would suggest it is not clear what "works as expected" means. You may know what to expect. But as a new user I don't.
The explanation would lead one to believe both phrases outside the php code would be outputted to the html document. I suspect that is not what happens, but I will need to go test it.
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"?>';'.
04-Apr-2006 04:58
just for conclusion:
<?php echo('<?xml version="1.0" ?'.'>'); ?>
is the right choice :)
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."\"?>";
?>
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'
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>" ?>
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.
24-Jul-2005 02:06
Just another more "feature" of IE...
Content-Disposition: attachment; filename=\"__FILE__\";
__FILE__ can't have spaces or :
Regards
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.
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.
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.
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.
20-Oct-2004 01: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");
?>
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.
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.
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).
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"?>
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">
//<![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.
07-Dec-2003 04: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");
?>
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/*<Some HTML>*/?> fails...
<?/*<Some HTML>*/?> works...
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"); ?>
