PHP JSON 字符串,为 JS 输出转义双引号
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7462394/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
PHP JSON String, escape Double Quotes for JS output
提问by Luke
I'm creating a JSON string from a PHP array. I've encoded it using json_encode()
.
我正在从 PHP 数组创建一个 JSON 字符串。我已经使用json_encode()
.
$data = array(
'title' => 'Example string\'s with "special" characters'
);
$data = json_encode( $data );
$data
is localized using wp_localize_script()
and is accessible via a global data
variable.
$data
使用本地化wp_localize_script()
并且可以通过全局data
变量访问。
In the JS file I can access the information by the following:
在 JS 文件中,我可以通过以下方式访问信息:
var data = data.replace( /"/g, '"' ),
jsonData = jQuery.parseJSON( data );
console.log( jsonData );
This results in an output of:
这导致输出:
{ "title":"Example string's with "special" characters" }
Entering that result into http://jsonlint.com/returns an error. Removing the double quotes around "special" validates the string.
将该结果输入http://jsonlint.com/ 会返回错误。删除“special”周围的双引号会验证字符串。
What is the best way to create a JSON string from PHP and properly escape it for use in a JS file?
从 PHP 创建 JSON 字符串并正确转义它以在 JS 文件中使用的最佳方法是什么?
采纳答案by Chris Eberle
From http://www.php.net/manual/en/function.json-encode.php#100565
来自http://www.php.net/manual/en/function.json-encode.php#100565
That said, quotes " will produce invalid JSON, but this is only an issue if you're using json_encode() and just expect PHP to magically escape your quotes. You need to do the escaping yourself.
也就是说,引号 " 会产生无效的 JSON,但这只是在您使用 json_encode() 并且只是希望 PHP 神奇地转义您的引号时才会出现的问题。您需要自己进行转义。
回答by Danny Thompson
Another way would be to encode the quotes using htmlspecialchars:
另一种方法是使用htmlspecialchars对引号进行编码:
$json_array = array(
'title' => 'Example string\'s with "special" characters'
);
$json_decode = htmlspecialchars(json_encode($json_array), ENT_QUOTES, 'UTF-8');
回答by Grégtheitroade Lafortune
I succefully just did this :
我成功地做到了这一点:
$json = str_replace("\u0022","\\\"",json_encode( $phpArray,JSON_HEX_QUOT));
json_encode()
by default will escape "
to \"
. But it's still wrong JSON for json.PARSE()
. So by adding option JSON_HEX_QUOT
, json_encode()
will replace "
with \u0022
. json.PARSE()
still will not like \u0022
. So then we need to replace \u0022
with \\"
. The \\\\\"
is escaped \\"
.
json_encode()
默认情况下将转义"
为\"
. 但是对于 .json 来说仍然是错误的 JSON json.PARSE()
。所以通过添加选项JSON_HEX_QUOT
,json_encode()
将替换"
为\u0022
. json.PARSE()
还是不会喜欢\u0022
。那么我们需要替换\u0022
为\\"
. 该\\\\\"
转义\\"
。
NOTE : you can add option JSON_HEX_APOS
to replace single quote with unicode HEX
value if you have javascript single quote issue.
注意:如果您有 javascript 单引号问题,您可以添加选项JSON_HEX_APOS
以用 unicodeHEX
值替换单引号。
ex: json_encode( $phpArray, JSON_HEX_APOS|JSON_HEX_QUOT ));
前任: json_encode( $phpArray, JSON_HEX_APOS|JSON_HEX_QUOT ));
回答by Effectiva
Use json_encode($json_array, JSON_HEX_QUOT);
since php 5.3: http://php.net/manual/en/json.constants.php
json_encode($json_array, JSON_HEX_QUOT);
从 php 5.3 开始使用:http: //php.net/manual/en/json.constants.php
回答by ScienceofSpock
I just ran into this problem and the actual issue was that I forgot to add a proper application/json header before spitting out the actual JSON data.
我刚刚遇到了这个问题,实际问题是我在吐出实际的 JSON 数据之前忘记添加一个正确的 application/json 标头。
header('Content-Type: application/json');
回答by appcropolis
This is a solutions that takes care of single and double quotes:
这是一个处理单引号和双引号的解决方案:
<?php
$php_data = array("title"=>"Example string's with \"special\" characters");
$escaped_data = json_encode( $php_data, JSON_HEX_QUOT|JSON_HEX_APOS );
$escaped_data = str_replace("\u0022", "\\"", $escaped_data );
$escaped_data = str_replace("\u0027", "\'", $escaped_data );
?>
<script>
// no need to use JSON.parse()...
var js_data = <?= $escaped_data ?>;
alert(js_data.title); // should alert `Example string's with "special" characters`
</script>
回答by Joe Okatch
I had challenge with users innocently entering and some using double quotes to define their content. I tweaked a couple of answers from this page and others to finally define my small little work-around
我遇到了用户无辜输入的挑战,有些用户使用双引号来定义他们的内容。我调整了这个页面和其他人的几个答案,最终定义了我的小解决方法
$products = array($ofDirtyArray);
if($products !=null) {
header("Content-type: application/json");
header('Content-Type: charset=utf-8');
array_walk_recursive($products, function(&$val) {
$val = html_entity_decode(htmlentities($val, ENT_QUOTES, "UTF-8"));
});
echo json_encode($products, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_NUMERIC_CHECK);
}
I hope it helps someone/someone improves it.
我希望它可以帮助某人/某人改进它。
回答by vinay
Error come on script not in HTML tags.
不在 HTML 标签中的脚本出现错误。
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<pre><?php ($_POST)?print_r($_POST):'' ?></pre>
<form method="POST">
<input type="text" name="name"><br>
<input type="email" name="email"><br>
<input type="time" name="time"><br>
<input type="date" name="date"><br>
<input type="hidden" name="id"><br>
<textarea name="detail"></textarea>
<input type="submit" value="Submit"><br>
</form>
<?php
/* data */
$data = [
'name'=>'loKESH"'."'\\",
'email'=>'[email protected]',
'time'=>date('H:i:00'),
'date'=>date('Y-m-d'),
'detail'=>'Try this var_dump(0=="ZERO") \ \"'." ' \\ ",
'id'=>123,
];
?>
<span style="display: none;" class="ajax-data"><?=json_encode($data)?></span>
<script type="text/javascript">
/* Error */
// var json = JSON.parse('<?=json_encode($data)?>');
/* Error solved */
var json = JSON.parse($('.ajax-data').html());
console.log(json)
/* automatically assigned value by name attr */
for(x in json){
$('[name="'+x+'"]').val(json[x]);
}
</script>