Display html code in PHP: Architecture
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:
<?php $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.
<?php ob_start(); readfile("html_template_tutorial.html"); $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.