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
People also ask

What is the most recommended method to pass PHP string data to JavaScript
ANS: The most recommended method is using PHP’s json_encode() function, often combined with htmlspecialchars() when embedding the output within HTML attributes, to ensure both data integrity and security against XSS attacks.
🌐
sqlpey.com
sqlpey.com › php › pass-php-string-to-javascript
Securely Pass PHP String Data to JavaScript Variables - …
Is it safe to use addslashes for passing PHP data to JavaScript
ANS: No, it is generally not safe to use addslashes() for passing PHP data to JavaScript, especially if the data might contain the sequence. This can allow for XSS attacks by prematurely closing the JavaScript block. json_encode() is a much safer alternative.
🌐
sqlpey.com
sqlpey.com › php › pass-php-string-to-javascript
Securely Pass PHP String Data to JavaScript Variables - …
Why should I avoid directly embedding PHP variables into JavaScript
ANS: Directly embedding PHP variables can lead to syntax errors if the string contains characters that have special meaning in JavaScript (like quotes or backslashes). More critically, it poses a significant security risk for cross-site scripting (XSS) if the PHP variable contains malicious code that is not properly escaped.
🌐
sqlpey.com
sqlpey.com › php › pass-php-string-to-javascript
Securely Pass PHP String Data to JavaScript Variables - …
🌐
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 = '"' .
🌐
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.
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
🌐
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
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)
🌐
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.
🌐
Our Code World
ourcodeworld.com › articles › read › 714 › how-to-print-safely-a-string-variable-from-php-in-javascript-with-symfony-1-4
How to print safely a string variable from PHP in JavaScript with Symfony 1.4 | Our Code World
March 31, 2018 - The one that we need to print safely a string from PHP inside a JavaScript context is the esc_js_no_entities method, this method escapes a string, making it suitable to be placed in a JavaScript string.