Using PHP and HTML on the Same Page

Working With PHP Inside HTML

Picture of HTML code on a blue background
virusowy/Getty Images

Want to add HTML to a PHP file? While HTML and PHP are two separate programming languages, you might want to use both of them on the same page to take advantage of what they both offer.

With one or both of these methods, you can easily embed HTML code in your PHP pages, to format them better and make them more user-friendly. The method you choose depends on your specific situation.

Use HTML Tags

Your first option is to build the page like a normal HTML web page with HTML tags, but instead of stopping there, use separate PHP tags to wrap up the PHP code. You can even put the PHP code in the middle if you close and reopen the <?php and ?> tags.

This method is especially useful if you have a lot of HTML code but want to also include PHP.

Here's an example of putting the HTML outside of the tags (PHP is bold here for emphasis):

 <html>
<title>HTML with PHP</title>
<body>
<h1>My Example</h1>
<?php
//your PHP code goes here
?>
<b>Here is some more HTML</b>
<?php
//more PHP code
?>
</body>
</html>

As you can see you can use any HTML you want without doing anything special or extra in your PHP file, as long as it's outside and separate from the PHP tags.

In other words, if you want to insert PHP code into an HTML file, just write the PHP anywhere you want so long as they're inside the PHP tags. Open a PHP tag with <?php and then close it with ?> like you see above.

Use PRINT or ECHO

This other way is basically the opposite; it's how you'd add HTML to a PHP file with PRINT or ECHO, where either command is used to simply print HTML on the page. With this method, you can include the HTML inside of the PHP tags.

This is a good method to use for adding HTML to PHP if you only have a line or so to do.

In this example, the HTML areas are bold:

 <?php
Echo "<html>";
Echo "<title>HTML With PHP</title>";
Echo "<b>My Example</b>";
//your php code here
Print "<i>Print works too!</i>";
?>

Much like the first example, PHP still works here regardless of using PRINT or ECHO to write HTML because the PHP code is still contained inside the proper PHP tags.