Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

What is the easiest way to encode a PHP string for output to a Javascript variable?

I have a PHP string which includes quotes and newlines. I need the contents of this string to be put into a Javascript variable.

Normally, I would just construct my Javascript in a PHP file, ala:

<script>
  var myvar = "<?php echo $myVarValue;?>";
</script>

However, this doesn't work when $myVarValue contains quotes or newlines.

share|improve this question

14 Answers

up vote 236 down vote accepted

Expanding on someone else's answer:

<script>
  var myvar = <?php echo json_encode($myVarValue); ?>;
</script>

This does require PHP 5.2.0 or greater.

share|improve this answer
5  
If you use UTF-8 that's the best solution by far. –  porneL Oct 13 '08 at 23:02
 
yep, that's exactly how i do it. –  Javier Feb 18 '09 at 3:56
2  
It is important that the implementation of json_encode escapes the forward slash. If it didn't, this wouldn't work if $myVarValue was "</script>". But json_encode does escape forward slashes, so we're good. –  Drew LeSueur Oct 1 '10 at 19:40
 
If you're not 5.2, try jsonwrapper from boutell.com boutell.com/scripts/jsonwrapper.html –  Tom Auger Dec 22 '10 at 22:57
 
Thanks. This just solved a problem for me. +1 –  Jason Gennaro Jul 24 '11 at 18:15
show 4 more comments

encode it with JSON

share|improve this answer
 
Probably the easiest way to get this to work 100% of the time. There are too many cases to cover otherwise. –  Abyss Knight Oct 3 '08 at 18:42
 
Json only works with UTF-8 Charset. So it is not a solution if your website is working in a non UTF-8 Encoding –  Nir Apr 27 '09 at 12:06
4  
@nir: on one hand, i don't know any reason to use any other encoding, on the other hand, a full JSON encoder also manages any needed charset conversion –  Javier Apr 28 '09 at 2:03

I have had a similar issue and understand that the following is the best solution:

<script>
    var myvar = decodeURIComponent("<?php echo rawurlencode($myVarValue); ?>");
</script>

However, the link that micahwittman posted suggests that there are some minor encoding differences. PHP's rawurlencode() function is supposed to comply with RFC 1738, while there appear to have been no such effort with Javascript's decodeURIComponent().

share|improve this answer
function escapeJavaScriptText($string)
{
    return str_replace("\n", '\n', str_replace('"', '\"', addcslashes(str_replace("\r", '', (string)$string), "\0..\37'\\")));
}
share|improve this answer

htmlspecialchars

Description

string htmlspecialchars ( string $string [, int $quote_style [, string $charset [, bool $double_encode ]]] )

Certain characters have special significance in HTML, and should be represented by HTML entities if they are to preserve their meanings. This function returns a string with some of these conversions made; the translations made are those most useful for everyday web programming. If you require all HTML character entities to be translated, use htmlentities() instead.

This function is useful in preventing user-supplied text from containing HTML markup, such as in a message board or guest book application.

The translations performed are:

* '&' (ampersand) becomes '&amp;'
* '"' (double quote) becomes '&quot;' when ENT_NOQUOTES is not set.
* ''' (single quote) becomes '&#039;' only when ENT_QUOTES is set.
* '<' (less than) becomes '&lt;'
* '>' (greater than) becomes '&gt;'

http://ca.php.net/htmlspecialchars

share|improve this answer
1  
This will only be the right solution if the content of the JS variable is actually supposed to be HTML, where a string token like &amp; has meaning. Otherwise, it might be best to not convert them to entities. –  Peter Bailey Oct 3 '08 at 18:48

You could try

<script type="text/javascript">
    myvar = unescape('<?=rawurlencode($myvar)?>');
</script>
share|improve this answer
 
Doesn't completely work. Try with this string::: I'm wondering "hey jude" 'cause 1 + 1 < 5 ::: we still get &lt; so not a 100% bidirectional transliteration –  Tom Auger Dec 22 '10 at 22:55

Micah's solution below worked for me as the site I had to customise was not in UTF-8, so I could not use json; I'd vote it up but my rep isn't high enough.

function escapeJavaScriptText($string) 
{ 
    return str_replace("\n", '\n', str_replace('"', '\"', addcslashes(str_replace("\r", '', (string)$string), "\0..\37'\\"))); 
} 
share|improve this answer
 
Me too! These two lines of code is the best thing that happened to php (at least IMHO). Thanks a lot!! –  rizalp1 Oct 26 '12 at 3:44
<script>
var myVar = <?php echo json_encode($myVarValue); ?>;
</script>

or

<script>
var myVar = <?= json_encode($myVarValue) ?>;
</script>
share|improve this answer
 
You must not enclose the encoded value in quotes. –  Salman A Jan 25 at 14:47

The paranoid version: Escaping every single character.

EDIT: The reason why json_encode() may not be appropriate is that sometimes, you need to prevent " to be generated, e.g.

<div onclick="alert(???)" />
share|improve this answer
 
Escaping every single character worked for me. json_encode doesn't handle backslashes very well. If you need to pass something like a regular expression from mysql to javascript as a parameter then this seems the best way. –  Ekim May 22 '12 at 4:05

Don't run it though addslashes(), if your in the context of the HTML page, the HTML parser can still see the tag, even mid string, and assume its the end of the JavaScript:

<?php
    $value = 'XXX</script><script>alert(document.cookie);</script>';
?>

<script type="text/javascript">
    var foo = <?= json_encode($value) ?>; // Use this
    var foo = '<?= addslashes($value) ?>'; // Avoid, allows XSS!
</script>
share|improve this answer

You can insert it into a hidden DIV, then assign the innerHTML of the DIV to your JavaScript variable. You don't have to worry about escaping anything. Just be sure not to put broken HTML in there.

share|improve this answer
 
"not to put broken HTML in there", that means escaping 'HTML entities' (at the very least '<' and '&') –  Javier Feb 18 '09 at 3:55
 
No, just don't close your container DIV prematurely. –  Diodeus Feb 18 '09 at 21:30

I'm not sure if this is bad practice or no, but my team and I have been using a mixed html, JS, and php solution. We start with the PHP string we want to pull into a JS variable, lets call it:

$someString

Next we use in-page hidden form elements, and have their value set as the string:

<form id="pagePhpVars" method="post">
<input type="hidden" name="phpString1" id="phpString1" value="'.$someString.'" />
</form>

Then its a simple matter of defining a JS var through document.getElementById:

<script type="text/javascript" charset="UTF-8">
    var moonUnitAlpha = document.getElementById('phpString1').value;
</script>

Now you can use the JS variable "moonUnitAlpha" anywhere you want to grab that PHP string value. This seems to work really well for us. We'll see if it holds up to heavy use.

share|improve this answer
 
I have been doing this in my previous projects. Next time, I will try to use jQuery data. –  wenbert Aug 27 '10 at 6:05
 
remember to htmlencode your $someString... and while this is fine for input @value's, you have to be extra careful with href/src/onclick type attributes (try to white-list), as they can go straight into using the javascript: protocol, which is not protected against with html encoded values. –  Craig Francis Oct 19 '12 at 9:55

If you use a templating engine to construct your HTML then you can fill it with what ever you want!

Check out XTemplates: http://www.phpxtemplate.org It's a nice, open source, lightweight, template engine.

Your HTML/JS there would look like this:

<script>
    var myvar = {$MyVarValue};
</script>
share|improve this answer

Just wanted to point out you can use utf8_encode() before passing the string to json_encode.

That's what i'm doing:

echo json_encode(utf8_encode($msg));


I wanted to post it as a comment, but i lack the 50 points needed for it

share|improve this answer

protected by Community May 18 '11 at 21:24

This question is protected to prevent "thanks!", "me too!", or spam answers by new users. To answer it, you must have earned at least 10 reputation on this site.

Not the answer you're looking for? Browse other questions tagged or ask your own question.