Submit your appAboutContact

Display html code in php: how to display html code with php

in this tutorial you'll learn some techniques to display html code in php. PHP is a great programming language that allows you to create dynamic pages by writing directly the HTML or Javascript code. PHP is on the basis of a lot of CMS like wordpress or joomla. In this tutorial you'll see how to display html code in PHP.


Display html code in PHP: Architecture

As soon as a browser call a web page with the Http request, the server receives the request and through the php module generates the dynamic content that is sent back to the browser. I've reported this architecture in the figure below. PHP can generates all the content you need, html code, javascript code, images, files.

PHP scheme


Use echo to generate the HTML code

The first method that allows you to generate the HTML content is the echo function. This function allows you to directly print everything you write. You can concatenate the string with the point operator. Here  an example of this method is reported: 


$date = date("Y-m-d",time());

echo '<b>The HTML code goes here</b><br />
      Today is: <font color="#47AFCD"><b>' . $date . '</b></font>';

As you can see from the above reported code, you can directly write inside the echo function the HTML code and concatenate the php variables too.


Use the output buffering to prepare the generated content

Another method that allows you to write the HTML code through PHP, is to write the html file as a static template and read it through PHP. Let's create a new HTML file called html_template_tutorial.html.

<b>The HTML code goes here</b><br />
Today is: <font color="#47AFCD"><b>%_TIME_%</b></font>

%_TIME_% is a placeholder for the PHP variable and this will dinamically replaced.

Let's write the PHP code.



$html_code = ob_get_clean();
$html_code = str_replace("%_TIME_%", date("Y-m-d",time()), $html_code);

echo $html_code;


ob_start and ob_get_clean allows you to manage the output buffering. ob_start tells PHP when the output buffer has started, while ob_get_clean gets the buffered output  and cleans it. We can associate this buffer to a PHP variable and edit it.

Leave a comment

Submit your appAboutContactPrivacy