作者:你眼眸下的伤谁能读懂UPV | 来源:互联网 | 2023-09-25 14:24
我想在Json中转换php字符串或数组,所以我使用了json_encode。但由于我的字符串是html内容,因此json转换会跳过html标签。
请检查以下代码
$test = array('name' => 'Header Images','template' => '{{#each images}}{{image_url}}{{/each}}');
print_r(json_encode($test,JSON_UnesCAPED_UNICODE));
结果:
{"name":"Header Images","template":"{{#each images}}{{image_url}}<\/span>{{\/each}}"}
这里的标签被跳过。我还使用了不带JSON_UnesCAPED_UNICODE的json_encode,但没有任何更改。
HTML标记是JSON的有效内容。这里发生的是您的浏览器将标签解释为标签(因为您只是将JSON输出到浏览器中)。
如果将代码更改为print_r(htmlspecialchars(json_encode($test,JSON_UNESCAPED_UNICODE)));
,您将看到标记确实包含在JSON中(或者,您也可以在浏览器中查看源代码,然后看到标记在其中)。
,
您的浏览器隐藏所有标签。使用htmlentities()查看所有标签。
$test = array('name' => 'Header Images','template' => '{{#each images}}{{image_url}}{{/each}}');
$test = json_encode($test);
print_r(htmlentities($test));
结果:
{"name":"Header Images","template":"{{#each images}}{{image_url}}<\/span>{{\/each}}"}