The Various Methods of Mixing PHP With HTML
There’s many situations where in HTML markup you needed dynamic content served from PHP. Let’s say for example you need a link but both it’s href and anchor text are dynamic which are stored in
$text variables. There’s a few different ways of achieving this:
A common approach is to use single quotes and escape out of HTML for all the variables. As you can see this starts to get tricky to read in even simple cases.
/* using single quotes in PHP */ echo '<a href="' . $link . '">' . $text . '</a>';
Another option would be to use double quotes which makes PHP interpret the variables inside the quotes. However, this can be sometimes be tricky to debug and results in slower performance as the interpreter has to look for variables when parsing the string.
/* using double quotes in PHP */ echo "<a href='$name'>$name</a>";
Another option is to drop in and out of PHP as needed. It’s certainly easy to read although it can get a little verbose.
<!-- using html with php tags --> <a href="<?php echo $link; ?>"><?php echo $text; ?></a>
Another option is to use
printf. This allows you to set placeholders which will be swapped out for variables when the string is parsed.
/* using printf */ printf('<a href="%s">%s</a>', $link, $text);
First we pass the HTML string along with placeholders, then we pass the two arguments. The
%s in the placeholders tell PHP to treat the variable as a string. Other types such as integer
%d can be used. For a full list see the docs.
printf approach also lets us do something called ‘argument swapping’, where we can add the variables into the string in a different order. This is useful if text needs to be internationalised as other languages may have different sentence structures.
/* example of argument swapping */ $object = 'ball'; $colour = 'red'; printf('The %s %s', $object, $colour); /* The red ball */ printf('The %2$s %1$s', $object, $colour); /* The ball red */
It also allows us to easily repeat the placeholders without needing to add in more arguments.
/* creating a dynamic email link */ $email = 'email@example.com'; printf('<a href="mailto:%1$s">%1$s</a>', $email);
Finally, PHP offers a similar function called
sprintf which returns the formatted string instead of outputting it. Using
sprintf instead of
printf can allow us to create clearer and easier to maintain code.
/* using sprintf */ $email = 'firstname.lastname@example.org'; $format = '<a href="mailto:%1$s">%1$s</a>'; echo sprintf($format, $email);