Adam Norris

Adam Norris

Front-End Developer

← Back to Blog

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 $link and $text variables. There’s a few different ways of achieving this:

Single Quotes

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>';

Double Quotes

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>";

Using Tags

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>

Using printf

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.

The 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 = 'someone@somewhere.com';
printf('<a href="mailto:%1$s">%1$s</a>', $email);

Using sprintf

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 = 'someone@somewhere.com';
$format = '<a href="mailto:%1$s">%1$s</a>';
echo sprintf($format, $email);