Expanding on someone else's answer:

<script>
  var myvar = <?= json_encode($myVarValue, JSON_UNESCAPED_UNICODE); ?>;
</script>

Using json_encode() requires:

  • PHP 5.2.0 or greater
  • $myVarValue encoded as UTF-8 (or US-ASCII, of course)

Since UTF-8 supports full Unicode, it should be safe to convert on the fly.

Please note that if you use this in html attributes like onclick, you need to pass the result of json_encode to htmlspecialchars(), like the following:

htmlspecialchars(json_encode($string), ENT_QUOTES);

or else you could get problems with, for example, &bar; in foo()&&bar; being interpreted as an HTML entity.

Answer from bobwienholt on Stack Overflow
🌐
Css-resources
css-resources.com › Convert-PHP-String-to-JavaScript-String.html
Convert PHP String to JavaScript String
<HTML> <HEAD> </HEAD> <body> <?php $temperatures="hot"; echo "Convert PHP String to JavaScript String"; echo "<br><br>"; echo "PHP string value"; echo "<br><br>"; echo $temperatures; $temp_hotter="now is the time for all good men to come to the aid of the party now is the time for all good men to come to the aid of the party now is the time for all good men to come to the aid of the party now is the time for all good men to come to the aid of the party now is the time for all good men to come to the aid of the party now is the time for all good men to come to the aid of the party now is the ti
🌐
GitHub
gist.github.com › Chengings › 9599473
Escape php string to javascript string · GitHub
Escape php string to javascript string. GitHub Gist: instantly share code, notes, and snippets.
🌐
Texelate
texelate.co.uk › blog › convert-php-strings-for-use-as-javascript-strings
Convert PHP strings for use as JavaScript strings | Texelate
Note that, depending on the context you may need to call htmlspecialchars on the string before sending it to the function. <?php function formatJavaScript($string, $doubleQuotesContext = true, $addQuotes = false) { // It must be a string else numbers get mangled $string = (string) $string; // Encode as standard JSON, double quotes $string = json_encode($string); // Remove " from start and end" $string = mb_substr($string, 1, -1); // If using single quotes, reaplce " with ' and escape if ($doubleQuotesContext === false) { // Remove \ from " $string = str_replace('\"', '"', $string); // Escape single quotes $string = str_replace("'", "\'", $string); } if ($addQuotes === true) { if ($doubleQuotesContext === true) { $string = '"' .
Find elsewhere
🌐
sqlpey
sqlpey.com › php › pass-php-string-to-javascript
Securely Pass PHP String Data to JavaScript Variables - …
July 22, 2025 - To further enhance security, especially when embedding the data within HTML attributes like onclick, it’s crucial to pass the JSON-encoded string through htmlspecialchars(). This function converts specific characters into their HTML entity equivalents, preventing them from being misinterpreted as HTML or JavaScript code. ... <?php $myVarValue = "This is a string with 'quotes' and <tags>."; ?> <script> // Safely embed the JSON-encoded string into a JavaScript variable var myJsVar = <?php echo json_encode($myVarValue); ?>; // For use in HTML attributes like onclick, ensure proper escaping var
Top answer
1 of 4
47

The value of the onclick attribute should be escaped like any other HTML attribute, using htmlspecialchars(). Actual Javascript strings inside the code should be encoded using json_encode(). For example:

<?php
$message = 'Some \' problematic \\ chars " ...';
$jscode = 'alert('.json_encode($message).');';
echo '<a onclick="' . htmlspecialchars($jscode) . '">Click me</a>';

That being said... onclick (or any other event) attributes are so 2005. Do yourself a favor and separate your javascript code from your html code, preferably to external file, and attach the events using DOM functions (or jQuery, which wraps it up nicely)

2 of 4
3

I'm really just re-wording what @Marshall House says here, but:

In HTML, a double quote (") will always end an attribute, regardless of a backslash - so it sees: onclick="var a = prompt('New value: ', 'aaaa\". The solution that @Marshall offers is to separate your code out into a function. This way you can print escaped PHP into it without a problem.

E.g.:

<script>
    // This is a function, wrapping your code to be called onclick.
    function doOnClickStuff() {
        // You should no longer need to escape your string. E.g.:
        //var a = prompt('new value:','<?php echo $rec[$i]; ?>');
        // Although the following could be safer
        var a = prompt('new value:',<?php json_encode($rec[$i]); ?>);
        if (a) { <!--javascript code--> }
        else { <!--javascript code--> }
    }
</script>
<someelement onclick="doOnClickStuff();"> <!-- this calls the javascript function doOnClickStuff, defined above -->
🌐
PageCrafter
pagecrafter.com › blog › how to pass a php variable to javascript – easy way
How to Pass a PHP Variable to JavaScript - Easy Way
July 9, 2024 - 4. The values of these PHP string variables have to be transferred into javascript variables for further processing by javascript (or exposing these values in HTML directly)
🌐
Stack Overflow
stackoverflow.com › questions › 32405856 › pass-string-from-php-to-javascript-function-in-html
Pass string from .php to Javascript function in .html - Stack Overflow
<!DOCTYPE html> <html> <head> <script> function showString(time) { if (time=="") { document.getElementById("txtHint").innerHTML=""; return; } if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp=new XMLHttpRequest(); } else { // code for IE6, IE5 xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange=function() { if (xmlhttp.readyState==4 && xmlhttp.status==200) { document.getElementById("txtHint").innerHTML=xmlhttp.responseText; } } xmlhttp.open("GET","getstring.php?q="+time,true); xmlhttp.send(); } </script> <script> var map, heatmap; va
🌐
PHP
php.net › manual › en › v8js.executestring.php
PHP: V8Js::executeString - Manual
public V8Js::executeString(string $script, string $identifier = "V8Js::executeString()", int $flags = V8Js::FLAG_NONE): mixed
🌐
Envato Tuts+
code.tutsplus.com › home › wordpress › theme development
How to Pass PHP Data and Strings to JavaScript in WordPress | Envato Tuts+
November 28, 2022 - String containing the JavaScript to be added. $position. Whether to add the inline script before the handle or after. So this function will add an inline script before or after your JavaScript code. Let's revise the example we discussed in the previous section with the wp_add_inline_script version. Now, our home and pleaseWaitLabel values can be accessed inside our jQuery library via the php_vars variable.