This guide will learn about two main ways to print HTML content on a PHP web application.
PHP Echo Function
If you know the basics of PHP and get output, you know about the echo method. It is used extensively in PHP to output values on the screen. Although the echo method does not behave like a function, more like a constructor, you can add parenthesis to the statement if required.
Like any other valid PHP statement, you terminate it with a semi-colon. The echo method will take the content inside the quotes and print it to the screen.
You can use the echo statement to print strings, variables, results from expressions and functions, and more.
The examples below show how to use the echo statement.
$var = 10;
echo "this is a string";
echo 10;
echo "value of var is $var";
?>
The above examples contain multiple statements that can print strings, numbers, and variable interpolation.
If you want to print multiple statements, you can specify each of them separated by comma as shown in the example below:
echo "Hello", "anotherone", "and another", "\n";
?>
To print HTML markup using the echo statement, we can pass the content to it as shown in the example below:
$version = "HTML5";
echo "<h1>This is valid <em>{$version}</em></h1>";
?>
The code above will print valid HTML content.
PHP Print Function
The other method we can use to print HTML markup in PHP is the print function.
It is similar to echo, except it behaves like a standard PHP function. It accepts a single argument meaning it can print a single string.
The following is a simple example of the print method.
print "Hello";
?>
Like echo, you can output strings, numbers, and variables using the print statement.
To print HTML content using the print statement, you can do:
print "<h1>This is HTML markup</h1>";
?>
The above should process the markup and display it accordingly.
If you want to learn how to print PHP values and variables inside HTML, check our tutorial on the topic.
Closing
This tutorial taught you how to print HTML markup inside a PHP file. This helps make the web page dynamic as you can fetch information from the server and display it on the browser.