gpt4 book ai didi

javascript - 如何在 PHP 中对 HTML 进行 JSON 编码?

转载 作者:行者123 更新时间:2023-12-01 01:13:34 26 4
gpt4 key购买 nike

我正在使用 AJAX 和 PHP 创建帖子并立即显示它。我的 php 代码可以创建帖子,但我在进行 json 编码以显示刚刚创建的帖子时遇到问题。像这样对 html 进行编码似乎会在每个/之前添加一个\,导致 html 中断并以奇怪的方式显示。 (我使用 json 编码,因为如果出现错误,我需要一个变量来知道它是否是错误,并将错误显示在与帖子不同的位置)

这是我要编码的内容

$data = "<article class='post'><div class='post-head cf'>
<a class='userpic' href=''><img src='$userpic' alt='".$rowuser['username']."'></a>
<a href='' class='username'>".$rowuser['username']."</a></div>
<img src='users/user_".$rowuser['user_id']."/posts/".$row['image']."' alt=''>
<div class='post-body'>
<div class='post-options'>
<a class='likes' href=''>156 likes</a>
</div>
<p><a class='username' href=''>".$rowuser['username']."</a>".$row['body']."</p>
<hr /><div class='cf'>
<a class='like hide-text' href='javascript:;'>Like This Post</a>
<form action='' class='comment'>
<input type='text' placeholder='Add a comment'></form></div>
</div></article>";

echo json_encode($data);

最佳答案

Encoding the html like this seems to add a \ before every / causing the html to break

PHP is escaping the slashes while encoding 。可以通过在调用 json_encode() 时添加 JSON_UNESCAPED_SLASHES 标志来防止这种情况:

$data = "<html></html>";

$escaped = json_encode($data);
// string(16) ""<html><\/html>""
var_dump($escaped);

$unescaped = json_encode($data, JSON_UNESCAPED_SLASHES);
// string(15) ""<html></html>""
var_dump($unescaped);

关于javascript - 如何在 PHP 中对 HTML 进行 JSON 编码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41349817/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com