Dutch PHP Conference 2025 - Call For Papers

Відмежування від 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 всередину XML чи XHTML, потрібно використовувати теги <?php ?>, щоб код відповідав стандартам цих розміток.

add a note

User Contributed Notes 3 notes

up
404
quickfur at quickfur dot ath dot cx
14 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
77
ravenswd at gmail dot com
15 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
27
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!
To Top