Home > Web Front-end > JS Tutorial > How Can I Safely Pass PHP Variables Containing Quotes and Newlines to JavaScript?

How Can I Safely Pass PHP Variables Containing Quotes and Newlines to JavaScript?

Linda Hamilton
Release: 2024-12-17 18:32:15
Original
369 people have browsed it

How Can I Safely Pass PHP Variables Containing Quotes and Newlines to JavaScript?

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>
Copy after login

This method requires:

  • PHP 5.2.0 or later
  • $myVarValue encoded in UTF-8

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);
    Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template