Skip to content

Everything for WordPress, web development — and beyond

HTML into PHP: echo, heredoc, nowdoc and leaving PHP

HTML into PHP: echo, heredoc, nowdoc and leaving PHP

Paste finished markup and you get five ways of putting it into a PHP file, each with the right escaping. Everything runs in your browser: the markup is never sent anywhere and never stored.

Drop an .html here — the file is read locally.
Markup handling

The closest thing to what codebeautify produces, but with escaping: without it any apostrophe in the markup breaks the PHP string.

Paste HTML above — the PHP code will appear here.

The markup never leaves your browser — the conversion runs locally, with nothing sent to a server.

Five methods and when each one fits

echo line by line — line after line, each in its own call. The most familiar look, handy when a condition or a loop has to go between the lines. nowdoc — a block in which PHP interprets nothing: neither escape sequences nor variables. The markup goes into the code byte for byte and needs no escaping at all. This is the safest way to move someone else's HTML. heredoc — the same block but with variables: $title inside gets substituted. That is why the dollar sign and the backslash are escaped while the quotes are not. A string in a variable — the markup is collected into $html by concatenation. Needed when it has to be returned from a function or passed to a template engine rather than printed straight away. Leaving PHP — close the tag and hand over the markup as it is. This is exactly what the PHP documentation recommends: no escaping, no cost of gluing strings together, and the editor's syntax highlighting keeps working. The closing ?> tag is deliberately absent from the generated code. Any character after it — even a stray newline at the end of the file — ends up in the output and produces the classic «headers already sent».

Why converters without escaping produce code that will not run

The most widespread online HTML-to-PHP converter does exactly one thing: it cuts the text into lines and glues together echo '<line>';. There is no character replacement there at all, and it shows on the very first real piece of markup. An attribute in single quotes — <a href='/price'> — closes the PHP string in the middle of the text. A syntax error follows. A backslash at the end of a line swallows the closing quote and glues two lines into one. A dollar sign inside double quotes or a heredoc turns $total into an empty value. trim() on every line silently strips the indentation inside pre, textarea and code — what the visitor sees on the page changes. All the lines are glued without breaks, so the resulting HTML becomes one endless line. Here every one of these cases is handled, and the heredoc label is chosen so that it does not coincide with any line of your markup: otherwise the block would close in the middle.

Frequently asked questions