Відмежування від HTML

Все, що за межами пари з відкриваючим та закриваючим тегами, ігнорується обробником PHP. Таким чином можна обробляти PHP-файли зі змішаним вмістом, тобто вбудовувати PHP-код в HTML-документи, наприклад, при створенні шаблонів.

<p>Ця частина коду буде проігнорована PHP, але показуватиметься через браузер.</p>
<?php echo 'В той час, як ця частина коду буде оброблятись.'?>
<p>І цей код - також буде проігноровано PHP, але показуватиметься через браузер.</p>
Такий код обробляється як і очікується, оскільки коли інтерпретатор PHP зустрічає закриваючий тег ?> він просто починає виводити все, що знаходить, допоки не зустріне інший відкриваючий тег. Але є два виключення, коли інтерпретатор не виводить вміст після закриваючого тега: по-перше, якщо безпосередньо далі йде символ нового рядка - про це можна прочитати на сторінці поділ інструкцій; і по-друге, якщо наступний код знаходиться всередині тіла умовного оператора (в такому разі інтерпретатор визначає результат в умові, перед тим як вирішити що потрібно виводити). Дивіться наступний приклад.

Приклад #1 Розмежування коду PHP та HTML з використанням умовних операторів

<?php if ($expression == true): ?>
  Цей текст буде показано, якщо змінна $expression матиме значення true,
  тобто вираз if ($expression == true) буде дійсним.
<?php else: ?>
  В противному разі буде виводитись цей текст.
<?php endif; ?>
В даному прикладі PHP буде пропускати ті блоки, де умова виразу не виконується, навіть не дивлячись на те, що ці блоки знаходяться за межами відкриваючого та закриваючого PHP-тегів, PHP-інтерпретатор просто перестрибуватиме їх.

Для виводу великих блоків текста, вихід з PHP-режиму є більш ефективним, ніж відправка всього текста через echo чи print.

Існує чотири різних пари з відкриваючими та закриваючими тегами, які можна використовувати в PHP. Дві із них, <?php ?> та <script language="php"> </script>, завжди доступні. Дві інші пари - це короткі теги та теги в стилі ASP, які можна включати та відключати у конфігураційному файлі php.ini. Отже, хоча деякі люди вважають зручними короткі теги та теги в стилі ASP, вони є менш портативними, та взагалі то не рекомендуються.

Зауваження:

Якщо ви вставляєте блоки PHP вередині XML чи XHTML, вам потрібно використовувати теги <?php ?> щоб код залишався сумісним згідно зі стандартом.

Приклад #2 Різні варіанти відкриваючих та закриваючих тегів PHP

1.  <?php echo 'якщо ви хочете обробляти PHP-код всередині XHTML або XML
                документів, використовуйте такі теги'
?>

2.  <script language="php">
        
echo 'деякі редактори (наприклад FrontPage) не обробляють інструкції
              всередині таких тегів'
;
    
</script>

3.  <? echo 'цей код знаходиться всередині коротких тегів PHP'?>
    А код в таких тегах <?= 'тут якийсь текст' ?>
    є скороченням для коду <? echo 'тут якийсь текст' ?>

4.  <% echo 'Також, якщо хочете, можете використовувати теги в ASP-стилі'; %>
    А код в таких тегах <%= $змінна; %>
    є скороченням для коду <% echo $змінна; %>

Хоча теги, показані в пунктах 1 та 2, завжди є доступними, теги, показані в пункті 1, є найбільш вживаними, та є рекомендованим, на відміну від тегів в пункті 2.

Короткі теги (пункт 3) є доступними, тільки якщо вони підключені через директиву short_open_tag в конфігураційному файлі php.ini, або якщо PHP було сконфігуровано з параметром --enable-short-tags .

Теги в стилі ASP (пункт 4) доступні, тільки коли вони підключені через директиву asp_tags в конфігураційному файлі php.ini.

Зауваження:

Використання коротких тегів краще уникати при розробці застосунків чи бібліотек, що призначаються для поширення, або при розміщенні скриптів на PHP-серверах, які знаходяться не під вашим контролем, оскільки короткі теги можуть не підтримуватись. Для портативності, переконайтесь, що ви не використовуєте короткі теги.

Зауваження:

У версіях PHP 5.2 та рініших, парсер не дозволяв використовувати тільки відкриваючі теги <?php без використання закриваючих тегів. Це стало можливим починаючи з PHP 5.3, при наявності одного чи кількох пробілів після відкриваючого тега.

Зауваження:

Починаючи з PHP 5.4, короткий тег <?= завжди розпізнається та є дійсним, незалежно від того, чи включена директива short_open_tag.

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