3

I pulling out some html/text strings that I need to insert into a javascript variable.

eg, that's how it would look in php:

echo "<script type=\"text/javascript\">\n";
echo "var myvar='{$value}'";
echo "\n</script>";

The problem with the above approach is that some special characters would actually break the javascript code.

So, I tried using htmlspecialchars:

htmlspecialchars($value,11,'utf-8',true); //11 stands for ENT_QUOTES|ENT_SUBSTITUTE

This did replace some unusual chars and most importantly the quotes.

However the new line chars pass it by and break my javascript.

So how could I escape the new line chars? I need to preserve them to be used later in the textareas.

*EDIT* I will post a sample value of my variable. (They are actually the input from Tiny_mce)

 <p>You've been...</p>
 <p><iframe src="http://www.youtube.com/embed/8d7OBluielc?wmode=transparent" frameborder="0" width="640" height="360"></iframe></p>
9
  • AJAX + JSON would be a "sane" solution. Commented Aug 18, 2012 at 8:35
  • Why are you talking about ajax? Commented Aug 18, 2012 at 8:36
  • @elclanrs Sorry but I don't understand. care to explain ? Commented Aug 18, 2012 at 8:37
  • @Anonymous if you show us an example for the content of $value it would help. Commented Aug 18, 2012 at 8:38
  • 1
    Instead of "\n", try PHP_EOL. Commented Aug 18, 2012 at 8:40

1 Answer 1

11
<script type="text/javascript">
    var myvar = <?php echo json_encode($value); ?>;
</script>

JSON == Javascript notation == the proper encoding/escaping method for any values output to Javascript.

Sign up to request clarification or add additional context in comments.

2 Comments

I have a question though, would it handle UTF-8 characters?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.