Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php echo without having to escape quotes

Is there a way to 'echo' / 'render HTML' and not have to escape every quote?

Kind of like how below the HTML below is being rendered without having to use echo or escape anything.

disregard any php syntax errors, example only

 <? if($a == $b) {;?> I said: "It's with quotes" <? ;} ?>
 <? else {;?> They said "It's still with quotes" <? ;} ?>

the reason for this is I need to echo a large Javascript file that uses both single and double quotes, and it would take forever to escape them all.

like image 502
Ghost Echo Avatar asked Feb 19 '26 10:02

Ghost Echo


2 Answers

Assuming you're just trying to display (not run) some code, you can use any of these two approaches:

  • Store the JavaScript file as a separate file, and use file_get_contents() to get the code and display it in <pre> code-blocks
  • Use the HEREDOC syntax to store the file contents

Approach #1:

$contents = file_get_contents('file.js');
echo '<pre>', $contents, '</pre>';

Approach #2:

$contents = <<<FILE

... contents ...

FILE;

echo '<pre>', $contents, '</pre>';

I'd go with the first approach though. That way, you won't clutter up your script with long JavaScript code that's not actually used for page rendering. It's usually a good idea to separate your logic into multiple files. In both cases though, you don't have to worry about quoting, at all.

like image 54
Amal Murali Avatar answered Feb 21 '26 00:02

Amal Murali


You can use HEREDOC syntax.

$str = <<<TEXT
I said: "It's with quotes"
TEXT;

The TEXT can be anything, as long as you use it on the opening line and the closing line:

$str = <<<ANYTHING
I said: "It's with quotes"
ANYTHING;
like image 33
crush Avatar answered Feb 21 '26 00:02

crush



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!