Passing PHP Variables to JavaScript Variables
Problem:
You need to transfer PHP strings containing quotes and newlines to JavaScript variables. Traditional methods like直接输出PHP代码 doesn't handle these special characters correctly.
Answer:
Using json_encode():
<script> var myvar = <?= json_encode($myVarValue, JSON_UNESCAPED_UNICODE); ?>; </script>
This method requires:
json_encode() converts the PHP string to a JSON representation while preserving Unicode characters.
Considerations:
If passing the JSON-encoded string to HTML attributes (e.g., onclick), ensure to pass it through htmlspecialchars() to avoid potential HTML entity issues.
htmlspecialchars(json_encode($string), ENT_QUOTES);
The above is the detailed content of How Can I Safely Pass PHP Variables Containing Quotes and Newlines to JavaScript?. For more information, please follow other related articles on the PHP Chinese website!