How to mix HTML code and PHP code in PHP document?

PHP is the server side script runs at server side and generates an HTML output. HTML is prepared by using HTML tags runs at client side by web-browsers. PHP parser allows HTML code along with its PHP code. But we need to maintain separate section to differentiate which one is PHP code.

Usually PHP code embed with in the <?php and ?> tags.

In order to use both HTML code and PHP code in your PHP document, you need to embed PHP code with in <?php and ?> tags and rest of the HTML code leave as it is.

Some time it is not possible to separate the HTML code from PHP code. So, place the HTML code inside PHP code and display HTML code with the help of PHP’s echo or print statements.

Altogether below is the sample code:

<body>
<?php 
	$var_doc_root = $_SERVER['DOCUMENT_ROOT'];
?>

<h2>Embed PHP Code within HTML Code: <?php echo $var_doc_root ?></h2>

<?php
echo "<h2>Embed HTML Code within PHP Code: " . $var_doc_root . "</h2";
?>

</body>

by Code Steps

Leave a Reply