Home >Web Front-end >JS Tutorial >How to Safely Encode PHP Strings for JavaScript Variables?
Question:
How to efficiently encode a PHP string containing special characters (e.g., quotes, newlines) for use in a JavaScript variable?
Answer:
To encode a PHP string, the recommended approach is to leverage the json_encode() function with the JSON_UNESCAPED_UNICODE flag:
<script> var myvar = <?= json_encode($myVarValue, JSON_UNESCAPED_UNICODE); ?>; </script>
Considerations:
Additional Notes:
htmlspecialchars(json_encode($string), ENT_QUOTES);
The above is the detailed content of How to Safely Encode PHP Strings for JavaScript Variables?. For more information, please follow other related articles on the PHP Chinese website!