Putting HTML inside PHP safely
When HTML has to be produced from PHP code (in a plugin, a legacy script or a helper function), every quote and dollar sign in the markup can break the string or trigger unwanted variable interpolation. This HTML to PHP converter wraps your markup in valid PHP and escapes exactly the characters that need it for the style you choose.
Output styles compared
For the input <span>$19.99</span> it's a deal:
// echo (single quotes)
echo ' <span>$19.99</span> it\'s a deal' . PHP_EOL;
// echo (double quotes)
echo " <span>\$19.99</span> it's a deal\n";
// variable
$html .= ' <span>$19.99</span> it\'s a deal' . PHP_EOL;
// heredoc
echo <<<HTML
<span>\$19.99</span> it's a deal
HTML;
// nowdoc
echo <<<'HTML'
<span>$19.99</span> it's a deal
HTML;- Echo – one
echoper line. Easy to read and to edit line by line. - Concatenation – a single
echostatement joined with., which keeps the output in one expression. - Variable – builds the markup in a variable (default
$html) with.=and echoes it at the end, handy when a function should return HTML instead of printing it. - Heredoc – keeps the HTML almost untouched between
<<<HTMLandHTML;. Variables inside heredoc are interpolated, so literal$signs are escaped. - Nowdoc – like heredoc but with a quoted label (
<<<'HTML'); nothing is interpolated, so no escaping at all is needed.
Single vs double quotes
In single-quoted PHP strings only \' and \\ are special, so the converter escapes those and adds PHP_EOL to keep line breaks. In double-quoted strings, ", \ and $ are escaped and each line ends with \n. Single quotes are slightly simpler and avoid accidental interpolation; double quotes let you insert variables later.
If a line in your HTML happens to equal the heredoc label, the converter automatically picks a different label (HTML_), so the block never ends early.
When to use which
- Short snippets inside logic: echo or concatenation.
- Functions that return markup: variable.
- Large static blocks: nowdoc, because it is the most readable and needs no escaping.
- Large blocks where you will add
{$variables}: heredoc.
A better long-term approach
For anything beyond small snippets, a template (a Blade or Twig view, or a plain PHP template file where HTML lives outside <?php ?> tags) is easier to maintain than HTML inside strings. And whenever you insert user data into HTML, escape it with htmlspecialchars() to prevent cross-site scripting. You can see what that escaping does with the HTML escape tool.
Tidy the markup first with the HTML formatter and the PHP result afterwards with the PHP formatter. Conversion happens in your browser.