11 Vote

PHP: Echo HTML code with both types of quotes without escape character

Question by Chematik | 2012-06-29 at 09:45

In PHP, I have often the problem, that I want to output long HTML sequences with "echo", that can contain both types of quotation marks, so " and '. For example, because there is JavaScript included in the string.

Let's take, for example, the following HTML code:

<input name="test" value="" onkeyup="$('#a').show();">

If I would like to output this HTML code with echo, for example with

echo '<input name="test" value="" onkeyup="$(\'#a\').show();">';

I had to escape the single quotes ' with \. With this small piece of code, it would not be so bad. But I have a lot of code and it would be very awkward to always write the escape character in it.

Is there not a better, more elegant solution?

ReplyPositiveNegative
0Best Answer0 Votes

Luckily, there is an elegant solution. The magic word is called "heredoc" or "nowdoc".

Here's an example for heredoc:

$foo='test';
 
echo <<<EOT
<p>This is an example for "heredoc" and
this is a variable '$foo'.</p>
EOT;

All that is written between "echo <<<EOT" and "EOT;" will be outputed. Also characters such as <, >, ' and " can be written down. It is important, that "echo <<<EOT" and "EOT;" are written at the beginning of the line and there are no other characters behind, even no spaces, because this will cause an error message. So, you can easily write your HTML code and beyond, you can also use variables, that are evaluated and outputed.

If you have do not want the variables to be evaluated, you can simply use the following syntax:

echo <<<'EOD'
<p>Here, variables will not be utilized</p>
EOD;

Already the variables are no longer evaluated. This variant is called nowdoc.
2012-06-29 at 18:16

ReplyPositive Negative
Reply

Related Topics

PHP: Sending an E-Mail

Tutorial | 0 Comments

PHP: Rounding Numbers

Tutorial | 0 Comments

Important Note

Please note: The contributions published on askingbox.com are contributions of users and should not substitute professional advice. They are not verified by independents and do not necessarily reflect the opinion of askingbox.com. Learn more.

Participate

Ask your own question or write your own article on askingbox.com. That’s how it’s done.