Create a picture counter


Hello! Today I will tell you how to dynamically create a picture like the one above using PHP. Everyone probably wondered how to implement this. It seems to me, if you think very well, then a new technology will come to mind that is being introduced, especially with the advent of HTML5. This, as many have probably guessed already - SVG. For those who don’t know, in fact, this is just an ordinary picture, but written in the form of XML. You can get a picture in two ways: draw it yourself, for example, in Inkscape, or download a ready-made one. I will use the second method, since I have neither time nor artistic talent. I will do as an example of personal messages / mail, so I need two pictures, the first - no messages, the second - we have a number of new messages. Download the pictures here . old.svg - no messages, new.svg there is a message.

So, we will pass to implementation. We will need:
  • Some knowledge of PHP and HTML
  • Understanding what a template engine is
  • Understanding What SVG Is

Download the template engine from here .
How does a template engine work? It works quite easily. We indicate the template to the class, initialize the variables, parsim, we get the code ready for output.
If in the code, it works something like this:
require_once('template.php'); // Подключаем шаблонизатор
$var = "Text";
$tpl->get_tpl('file.html');
$tpl->set_value('Var',$var);
$tpl->tpl_parse();

In the same way we will work with our pictures. First, open the karinka new.svg, for example, in notepad. Find the line at the very end of the file:
1

And change to:
{MSG}

With these steps, we added a variable to the template. Now that we have the picture template, we move on to the function itself. Before writing, you need to be aware that we have two pictures and we need to think about which one to display depending on the value of the variable. Then substitute this value into the template and get a simple code:
		// Подключаем шаблонизатор
		require_once('template.php'); // Подключаем шаблонизатор
		$number = 1;
		if ($number == 1){ // Новое сообщение
			$tpl->get_tpl('imgs/new.svg');
			$tpl->set_value('MSG',$number);
			$tpl->tpl_parse();
			echo $tpl->html;
		}
		else{ // Сообщений нет
			$tpl->get_tpl('imgs/old.svg');
			$tpl->tpl_parse();
			echo $tpl->html;
		}

Note that the pictures are in the imgs subdirectory, and the template engine is next to the script in which it is connected.
That's all! A simple solution, a simple problem.
PS: Sorry for the new.svg picture. I can’t draw, if you don’t like to correct it.

Also popular now: