Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
PHP Escaping From HTML
PHP allows you to seamlessly mix PHP code with HTML in a single file. When PHP encounters opening <?php tags, it executes the PHP code, and everything outside these tags is treated as HTML and sent directly to the browser.
Syntax
<p> HTML block </p> <?php //PHP block .. .. ?> <p> HTML block </p> <?php //PHP block .. .. ?> <p> HTML block </p>
Every time the PHP parser encounters an opening tag, it starts executing PHP code until it reaches the closing tag. When PHP code contains conditional statements, the parser determines which blocks to execute or skip. Everything outside PHP tags is treated as HTML and processed by the browser.
Basic Example
The following example demonstrates PHP code embedded within HTML −
<html>
<body>
<!-- HTML code -->
<h3>Hello World</h3>
<!-- PHP code -->
<?php
echo "Hello World in PHP";
?>
<!-- This is HTML code -->
<p>Hello world again</p>
<?php
echo "Hello World again in PHP";
?>
</body>
</html>
Output
Hello World Hello World in PHP Hello world again Hello World again in PHP
Using Conditional Statements
PHP's alternative syntax for control structures works well with HTML embedding −
<?php $marks = 40; ?>
<h1>Using conditional statement</h1>
<?php if ($marks >= 50): ?>
<h2 style="color:blue;">Result: Pass</h2>
<?php else: ?>
<h2 style="color:red;">Result: Fail</h2>
<?php endif; ?>
Output
Using conditional statement Result: Fail
If you change $marks to 60 and run again, the output will show "Result: Pass" in blue color.
Key Points
- HTML content outside PHP tags is sent directly to the browser
- PHP code is executed on the server before sending output to the client
- You can have multiple PHP blocks in a single file
- Alternative syntax (
if:,endif;) is useful for mixing PHP with HTML
Conclusion
Escaping from HTML in PHP allows you to create dynamic web pages by mixing server−side PHP logic with client−side HTML. This feature makes PHP particularly suitable for web development, enabling conditional content rendering and dynamic HTML generation.
