HTML에서 벗어나기

PHP가 파일을 해석할 때, PHP가 사이에 있는 코드를 해석하라고 하는 시작과 끝 태그를 찾습니다. 이런 방법의 해석은, 시작과 끝 태그 밖에 있는 부분은 PHP 해석기가 무시하게 됨으로써, php가 어떠한 종료의 문서에도 포함될 수 있도록 합니다. 대부분의 경우 다음 예제와 같이 php가 포함된 HTML 문서를 보게 될 것입니다.

<p>이 부분은 무시합니다.</p>
<?php echo '이 부분은 해석합니다.'?>
<p>이 부분도 무시합니다.</p>

좀 더 복잡한 구조도 사용할 수 있습니다:

Example #1 복잡한 벗어나기

<?php
if ($expression) {
    
?>
    <strong>This is true.</strong>
    <?php
} else {
    
?>
    <strong>This is false.</strong>
    <?php
}
?>
예상한 대로 작동합니다. PHP가 ?> 닫기 태그를 만나면, 그것이 무엇이던간에 다른 시작 태그를 만나기 전까지 단순히 출력하기 때문입니다. (바로 따라오는 줄바꿈 제외 - 명령 구분 참고) 물론, 여기서 주어진 예제는 부자연스럽지만 큰 텍스트 블록을 출력할 경우에는 PHP 해석 모드를 벗어나는 것이 모든 텍스트를 echoprint를 통하여 전송하는 것보다 효율적입니다.

php에서 사용할 수 있는 네가지 형태의 시작과 끝 태그가 있습니다. 그 중 두가지, <?php ?>와 <script language="php"> </script>는 항상 사용할 수 있습니다. 두가지 짧은 태그와 ASP 형식 태그는 php.ini 설정 파일에서 끄거나 켤 수 있습니다. 그러므로, 몇몇 사람들에겐 짧은 태그나 ASP 형식 태그가 편할지는 몰라도, 이식성이 부족하므로 일반적으로 권하지 않습니다.

Note:

PHP를 XML이나 XHTML에 넣을 경우 <?php ?> 태그를 사용해야 표준과 호환을 유지할 수 있습니다.

Example #2 PHP 시작과 끝 태그

1.  <?php echo 'XHTML나 XML 문서와 호환시키려면, 이렇게 쓰세요'?>

2.  <script language="php">
        
echo '어떤 에디터 (프론트페이지같은)는 
              처리 명령을 좋아하지 않습니다'
;
    
</script>

3.  <? echo '이런 형태가 제일 간단한 SGML 처리명령입니다'?>
    <?= expression ?>은 "<? echo expression ?>"을 간단히 쓴 모양입니다

4.  <% echo ("ASP스타일 태그를 쓸 수도 있습니다"); %>
    <%= $variable; # 이것은 "<% echo . . ." %>을 간단히 쓴 모양입니다

예제에서 볼 수 있는 태그 중 첫번째와 두번째는 항상 사용할 수 있지만, 둘 중 첫번째 예제가 가장 보편적으로 사용되며, 권장됩니다.

짧은 태그(예제 3)은 php.ini 설정 파일 지시어 short_open_tag를 활성화하거나, php를 --enable-short-tags 옵션으로 설정하였을 경우에만 사용할 수 있습니다.

ASP 형식 태그(예제 4)는 php.ini 설정 파일 지시어 asp_tags를 활성화 했을 경우에만 사용할 수 있습니다.

Note:

프로그램이나 재사용을 위한 라이브러리를 개발할때, 또는 통제밖의 PHP서버에 배치시킬때는 짧은 형 태그를 쓰는것은 피해야 한다. 왜냐하면 짧은 형 태그는 목표하는 서버에서 지원되지 않을수도 있기 때문이다. 이식성을 위해서, 재사용 코드는 짧은 형 태그로 쓰지 않도록 한다.

add a note add a note

User Contributed Notes 11 notes

up
392
quickfur at quickfur dot ath dot cx
13 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
76
ravenswd at gmail dot com
14 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
34
sgurukrupa at gmail dot com
10 years ago
Although not specifically pointed out in the main text, escaping from HTML also applies to other control statements:

<?php for ($i = 0; $i < 5; ++$i): ?>
Hello, there!
<?php endfor; ?>

When the above code snippet is executed we get the following output:

Hello, there!
Hello, there!
Hello, there!
Hello, there!
up
4
davidhcefx
3 years ago
When the PHP interpreter hits the ?> closing tags, it WON'T output right away if it's inside of a conditional statement:
(no matter if it's an Alternative Syntax or not)

<html>
<?php
$a
= 1;
$b = 2;
if (
$a === 1) {
    if (
$b == 2) {
       
?><head></head><?php
   
} else {
       
?><body></body><?php
   
}
}
?>
</html>

This would output `<html><head></head></html>`.
Aside from conditional statements, the PHP interpreter also skip over functions! What a surprise!

<html>
<?php
function show($a) {
   
?>
    <a href="https://www.<?php echo $a ?>.com">
    Link
    </a>
    <?php
}
?>
<body>
    <?php show("google") ?>
</body>
</html>

This gives `<html><body><a href="https://www.google.com">Link</a></body></html>`.
These really confused me, because at first I thought it would output any HTML code right away, except for Alternative Syntaxes (https://www.php.net/manual/en/control-structures.alternative-syntax.php). There are more strange cases than I thought.
up
6
anisgazig at gmail dot com
4 years ago
Version of  7.0.0,3 tags are available in php.
1.long form tag (<?php ?>)
2.short echo tag(<?= ?>)
3.short_open_tag(? ?)
You can use short_open_tag when you start xml with php.
up
27
snor_007 at hotmail dot com
14 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
-6
mike at clove dot com
13 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
-10
Emil Cataranciuc
6 years ago
"<script language="php"> </script>, are always available." since PHP 7.0.0 is no longer true. These are removed along the ASP "<%, %>, <%=" tags.
up
-3
Anonymous
3 years ago
Since it's not documented (AFAICT) and it might cause confusion: a single line break immediately after ?> is ignored. Since whitespace is hard to see, whitespace is replaced with _ and the following code

<?php echo '1'; ?>
<?php
echo '2'; ?>_
<?php echo '3'; ?>
_<?php echo '4'; ?>_<?php echo '5'; ?>

will produce

12_
3_4_5
up
-8
anisgazig.com
3 years ago
<p>This is ignore by the php parser and displayed by the browser </p>

<?php echo "While this is going to be parsed"; ?>

<?php

when php interpreter hits the closing tag it start to outputing everything whatever it finds until it hit another opening tag
.If php interpreter find a conditional statement in the middle of a block then php interpreter decided which block skip 

Advanced escaping using conditions

 
<?php $a = 10; if($a<100): ?>
  This conditional block is executed
  <?php else: ?>
      otherwise this will be executed
      <?php endif; ?>

In php 5 version,there are 5 opening and closing tags.
1.<?php echo "standard long form php tag and if you use xml with php this tag will be use";?>

2.<?= "short echo tag and alwayes available from 5.4.0";?>

3.<? echo "short open tag which is available if short_open_tag is enable in php ini configuration file directive or php was configured with --enable-short-tags.This tag has discoursed from php 7.If you want to use xml with php,then short_open_tag in php ini will be disabled";?>

4.<script language="php">
echo "Some editor do not like processing the code within this tag and this tag is removed from php 7.0.0 version";

</script>

5.<% echo "asp style tag and asp_tags should be enabled but now php 7.0.0 version,this tag is removed";%>
up
-56
admin at furutsuzeru dot net
15 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.
To Top