Output HTML From Your PHP Script

In this tutorial, I’ll show you how to output HTML from a PHP script.

This is very similar to our tutorial on outputting text using PHP (for example, creating your first script to output the text “hello world”), but we’ll be looking at HTML. HTML is the language of the web, so you’ll encounter it frequently when building websites.

PHP Script to Output HTML

Create a file called html.php with the following code and upload it to your webserver

<?php
echo "<h1>Hello World!</h1>";
?>

The output of this is the following HTML:

<h1>Hello World</h1>

Which looks like the following when you view it in the browser:

Hello World

Explanation of code to output HTML

Here, we use the echo command to send text to the browser, but the text contains HTML tags. The browser will recognise this as HTML and format the page as you tell it – here the <h2> tag will mean that the text Hello World! is formatted as a heading.

As before we saw in the previous tutorial, the <?php and ?> tags open execution of PHP code, the echo command says to output some text (i.e. send it to the browser), and we follow it with the string “<h1>Hello World</h1>", which contains HTML code.

We should say that the above code doesn’t really utilise PHP to do anything interesting – it just prints out text, which you could have done with a static HTML page. However, we’ll be able to build on this to do more interesting things soon.

Special Characters

You might need to output some characters such as quotation marks " in your HTML, but you will notice that we used those to mark the start and end of the string above. So how does PHP distinguish between the " which marks the start of the string, and that which is part of it? You can do this using a backslash (\) before the quotation mark which is part of the string: \". This is known as an escape character.

Alternatively, you can use single quotes ' to mark the start and end of the string, and double quotes within the string will be output without any special treatment. You can see these in the examples below, which both result in the same HTML being output:

<?php
echo '<img src="hello.jpg">';
echo "<img src=\"hello.jpg\">";
?>

Line Breaks

If you want to add a new line, you can do this using the \n special character (in a string which starts and ends with ". But remember, this will only show up in the source code of the page (which is the same as if you press enter when writing HTML code by hand), and won’t affect how it is shown to the visitor. If you want to add a new line which the visitor can see, use HTML to format it – such as the line break <br>.

{% highlight php %}

<?php
echo "<p>Hello \nWorld</p>";
echo "<p>Hello <br>World</p>";
?>

This example produces the following HTML source:

<p>Hello 
World</p>
<p>Hello <br>World</p>

But it looks like the following to a visitor in a web browser – note the line breaks are different to those in the source code:

hello world with line breaks