Logo Simple HTML template parser tutorial

A parser is a program that runs through a document of some sort and tries to alter this document based on parameters or with the use of a template with placeholders inside to make usefull dynamic content.
This tutorial is about creating a template file with placeholders and use a parser (which we will also create) to run through this template and replace all placeholders with usefull data.

The HTML template parser we will make, takes in a key/value pair array as an argument and runs through the premade template containing placeholders in the format, ##key##. The parser then compares each key from the array with the placeholder (##key##) and replaces this placeholder with the corresponding value from the array.

The project holds four files (The links take you to the final, complete source code of each respective file):

Let's first have a look at the parser itself. Create a file called parser.php.
We need an object (class). Let's call it Template. Add it inside the file we created (parser.php):

PHP code

<?php class Template { } ?>

In here we'll add a function to retrieve the contents from our template file (we haven't created the template file template.html just yet, but we'll look into that later). This is a simple function that takes a filename as an argument, checks if the file actually exists and returns the content. If it doesn't exist, return a simple string with an error message:

PHP code

<?php class Template { function get_file_content($file_name){ if (file_exists($file_name)) { $content = file_get_contents($file_name); } else { $content = "Tried to open the file: \"$file_name\", but I can't find it!"; } return $content; } } ?>

Now all we need to do is add the function that parses the template.

This function will take two arguments, the template content and an array to compare and replace placeholders found in the templates content.

To find the placeholders, we'll loop through the array and for each key in the array we'll call an inbuild PHP function called str_replace.

str_replace takes three arguments (actually it can take four, but the fourth argument is not needed since it only returns the number of values replaced) like so:

str_replace(Argument1, Argument2, Argument3);

  • Argument1: The string to search for. In our case the key from the array surrounded by hashtags (#).
  • Argument2: The string to replace the found string with. For us it's the value corresponding to the key in the array.
  • Argument3: The whole string to search and replace in. This would be our template content.

When done, it should return the new content, with all placeholders replaced:

PHP code

function parse($template_content, $placeholder_data){ foreach ($placeholder_data as $placeholder_key => $placeholder_value) { $template_content = str_replace("##$placeholder_key##", $placeholder_value, $template_content); } return $template_content; }

The final parser should look something like this:

PHP code - parser.php

<?php class Template { //Get file content (from "$file_name") function get_file_content($file_name){ if (file_exists($file_name)) { $content = file_get_contents($file_name); } else { $content = "Tried to open the file: \"$file_name\", but I can't find it!"; } return $content; } //Replace all matching placeholders in content with corresponding data values from array function parse($template_content, $placeholder_data){ foreach ($placeholder_data as $placeholder_key => $placeholder_value) { $template_content = str_replace("##$placeholder_key##", $placeholder_value, $template_content); } return $template_content; } } ?>

Now that we have created an engine that parses data recieved, we need to create content to actually pass to this engine so the engine can process it.

And what do we need? We need a template and an array with key, value pairs. Let's start easy and create the array. We could create the array directly, like this:

(don't use this code though, we'll use a better example. Read on!)

PHP code

$content_array = array( "main-title" => "My parser", "title" => "My first parser", "content" => "This is my first parser. Hope I can get it to work..." );

Our parser function (created earlier) takes an array as an argument (any array, as long as they have a key and a value), so we could get this array from a number of different sources like, an SQL database, an XML file, JSON, whatever. For the sake of this tutorial, using a database as an example is probably too comprehensive, so let's do it with JSON.
Create a file called content.json and put the following code in it.
To briefly explain, the value to the left, before the colon (:) is known as the key.
The value to the right is known as the value, hence the expression key, value pair (it's the same for the PHP array above):

JSON code - content.json

{ "main-title": "My parser", "title": "My first parser", "content": "This is my first parser. Hope I can get it to work..." }

Now that we have created the array, it's time for the template. This is just an ordinary HTML file (could be named anything you want).
Create a file called template.html and add HTML content to it, like below. We will add placeholders to the template file in the format ##placeholder## where the placeholder values should match the key from our array.
For example My parser would match main-title in the array we created just before (the array in the file "content.json"). We can create as many placeholders as we want/need, with any string value inside, as long as we add them in the array as well:

HTML code - template.html

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>##main-title##</title> </head> <body> <h1>##title##</h1> <p>##content##</p> </body> </html>

With the parser created and the template file and the array created as well, we are now ready to put it all together and make it work.
Create a PHP file named build.php and insert this line. It will include the contents of the file parser.php so we can access the engines functionality:

PHP code

include ("parser.php");

These two lines will respectively create the Template object and load the template files content.
Add the lines after the include line above:

PHP code

$content = new Template(); $content_template = $content->get_file_content("template.html");

Insert these two lines, which will load in the previously created JSON content and store it as a PHP array:

PHP code

$data_json = $content->get_file_content("content.json"); $content_json = json_decode($data_json);

Here we parse the template contents. We have to pass in the PHP array and the template contents:

PHP code

$parsed_content = $content->parse($content_json, $content_template);

Lastly we'll output the result so it will actually show up in the browser:

PHP code

echo $parsed_content;

You should at this point have a build.php file containing something like this (I've added comments explaining each line of code):

PHP code - build.php

<?php //Includes the content of "parser.php" include ("parser.php"); //Create the content object $content = new Template(); //Get content from template file $content_template = $content->get_file_content("template.html"); //Get contents of "content.json" (the array) $data_json = $content->get_file_content("content.json"); //Convert the JSON array to a PHP array $content_json = json_decode($data_json); //Parse the content $parsed_content = $content->parse($content_template, $content_json); //Output the final result echo $parsed_content; ?>

All that's left to do is test our parser. Navigate to build.php in your browser (I assume you have a server or a web host running PHP)
You should see something simple like this:

HTML result - Result

My first parser

This is my first parser. Hope I can get it to work...

If you are here, followed along with the tutorial and actually made it work, then... well, congratulations to you, you are awesome :-)