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, 24 Jul 2009

view this page in

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 해석 모드를 벗어나는 것이 모든 텍스트를 echo()print()를 통하여 전송하는 것보다 효율적입니다.

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서버에 배치시킬때는 짧은 형 태그를 쓰는것은 피해야 한다. 왜냐하면 짧은 형 태그는 목표하는 서버에서 지원되지 않을수도 있기 때문이다. 이식성을 위해서, 재사용 코드는 짧은 형 태그로 쓰지 않도록 한다.



명령 구분> <기본 문법
Last updated: Fri, 24 Jul 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, 24 Jul 2009
 
 
show source | credits | stats | sitemap | contact | advertising | mirror sites