NateShoffner
NateShoffner

Reputation: 16829

PHP string within JavaScript

I currently am trying to echo the contents of a text file within JavaScript. Everything works but there is a problem. The text within the text contains apostrophes, which is throwing everything off. Below is a portion of the code that I am using. I am using this code for MANY text files. I have considered changing each apostrophe to "\'" in each text file, but there are a lot of text files to deal with. I was just curious if there was another way to work around this. Any ideas are greatly appreciated.

<?php
     $lyrics = file_get_contents('Includes/Songs/Lose_My_Mind.txt');
?>

JavaScript snippet:

var scrollercontent='<?php echo $lyrics; ?>'

Upvotes: 0

Views: 394

Answers (7)

Julio
Julio

Reputation: 1

<?php
$lyrics = nl2br(htmlentities(file_get_contents('Includes/Songs/Lose_My_Mind.txt'), ENT_QUOTES)); 
?>
var scrollercontent="<?php echo $lyrics; ?>";

Upvotes: 0

bng44270
bng44270

Reputation: 349

You could add the following line after your file_get_contents command:

$lyrics = str_replace("\'","\\'",$lyrics);

This will change all of the single apostrophes to escaped apostrophes and should play nice with Javascript.

Upvotes: 0

jbnunn
jbnunn

Reputation: 6355

Try

addslashes(nl2br($lyrics))

(nl2br replaces new lines with <br> tags.)

Upvotes: 1

bobince
bobince

Reputation: 536389

Whilst addslashes will mostly work, this is better:

var scrollercontent= <?php echo json_encode($lyrics, JSON_HEX_TAG); ?>;

json_encode works for any datatype, not just strings. For strings it adds the quotes at the sides for you, and it will work for any character including control codes such as the newline character.

The JSON_HEXs are a PHP 5.3 feature. HEX_TAG replaces < with a JavaScript string literal encoding like \x3C, which means you can put any string literal in a <script> block without worrying that it might contain a </script> sequence that would prematurely end the script block. (Even just </ on its own is technically invalid.)

Upvotes: 4

Christopher Altman
Christopher Altman

Reputation: 4896

Have you tried:

<?php $lyrics = addslashes(file_get_contents('Includes/Songs/Lose_My_Mind.txt')); ?>

Upvotes: 0

Chris Gutierrez
Chris Gutierrez

Reputation: 4755

Try changing this

var scrollercontent='<?php echo $lyrics; ?>'

to this

var scrollercontent='<?php echo addslashes($lyrics); ?>'

or

var scrollercontent='<?php echo htmlentities($lyrics); ?>'

these should help escape or entitize quotes etc...

Upvotes: 0

Alex
Alex

Reputation: 3190

Try to use addslashes() function. In your case:

var scrollercontent='<?php echo addslashes($lyrics); ?>'

Upvotes: 2

Related Questions