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
Linda HamiltonOriginal
2024-12-17 18:32:15424browse

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>

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);

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!

Statement:
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