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 ec开发者_StackOverflow社区ho $lyrics; ?>'
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_HEX
s 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.)
Try to use addslashes() function. In your case:
var scrollercontent='<?php echo addslashes($lyrics); ?>'
Try
addslashes(nl2br($lyrics))
(nl2br
replaces new lines with <br>
tags.)
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...
Have you tried:
<?php $lyrics = addslashes(file_get_contents('Includes/Songs/Lose_My_Mind.txt')); ?>
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.
<?php
$lyrics = nl2br(htmlentities(file_get_contents('Includes/Songs/Lose_My_Mind.txt'), ENT_QUOTES));
?>
var scrollercontent="<?php echo $lyrics; ?>";
精彩评论