加入收藏 | 设为首页 | 会员中心 | 我要投稿 安卓应用网 (https://www.0791zz.com/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > PHP > 正文

PHP JSON字符串,转义JS输出的双引号

发布时间:2020-05-22 11:40:13 所属栏目:PHP 来源:互联网
导读:我正在从一个 PHP数组创建一个JSON字符串.我已经使用json_encode()编码了它. $json_array = array( title = Example strings with special characters);$json_decode = json_encode( $json_array ); 在JS文件中,我可以通过以下方式访问信息: 注

我正在从一个 PHP数组创建一个JSON字符串.我已经使用json_encode()编码了它.

$json_array = array(
    'title' => 'Example string's with "special" characters'
);

$json_decode = json_encode( $json_array );

在JS文件中,我可以通过以下方式访问信息:
注意:$json_decode使用wp_localize_script()本地化到全局变量php_params

var discographyJsonString = php_params.playlist_setup.replace( /"/g,'"' ),discographyJson = jQuery.parseJSON( discographyJsonString );

console.log(discographyJson);

输出结果为:

{ "title":"Example string's with "special" characters" }

如果将该结果输入http://jsonlint.com/,您将收到错误.如果您在“特殊”周围取出双引号,则表示有效.

从PHP中创建JSON字符串的最佳方式是什么,并将其转义为正确使用在JS文件中?

注意:这是参考我的另一篇文章,我从使用PHP的API中获取信息,用于JS:Loop through JSON string and create dynamic JS output

从 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.

(编辑:安卓应用网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读