gpt4 book ai didi

php - 如何在 PHP 中将 HTML 代码添加到 JSON?

转载 作者:行者123 更新时间:2023-12-05 03:15:45 27 4
gpt4 key购买 nike

我需要使用 PHP 将以下 html 代码添加到 JSON。

<a class="btn btn-mini btn-success" data-toggle="modal" href="#?page=customers-database-edit&id=$1">Edit</a>

如果我直接添加它会破坏包含双引号 (") 的 JSON 代码。

所以我尝试使用下面的代码:

if(is_string($result))
{
static $jsonReplaces = array(array('\\', '/', '\n', '\t', '\r', '\b', '\f', '"'), array('\\\\', '\\/', '\\n', '\\t', '\\r', '\\b', '\\f', '\"'));
return '"' . str_replace($jsonReplaces[0], $jsonReplaces[1], $result) . '"';
}
else
return $result;

以上代码生成的 html 是错误的方式:

<a class="\&quot;btn" btn-mini="" btn-success\"="" data-toggle="\&quot;modal\&quot;" href="\&quot;?page=customers-database-edit&amp;id=3\&quot;">Edit&lt;\/a&gt; \n</a>

最佳答案

引号对json没问题。你只需要依靠编码功能。

我制作了这个简单的测试脚本,它对一个数组进行编码并输出,json 编码的字符串和再次解码字符串生成的数组。这证明你得到了你输入的内容,不管它是否包含引号。

测试脚本:

<?php
$test=array(
1=>'one',
2=>'<a class="btn btn-mini btn-success" data-toggle="modal" href="#?page=customers-database-edit&id=$1">Edit</a>',
3=>'three'
);
$json=json_encode($test);
echo $json."\n\n";
echo print_r(json_decode($json));
?>

输出:

{"1":"one","2":"<a class=\"btn btn-mini btn-success\" data-toggle=\"modal\" href=\"#?page=customers-database-edit&id=$1\">Edit<\/a>","3":"three"}

stdClass Object
(
[1] => one
[2] => <a class="btn btn-mini btn-success" data-toggle="modal" href="#?page=customers-database-edit&id=$1">Edit</a>
[3] => three
)

关于php - 如何在 PHP 中将 HTML 代码添加到 JSON?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12339497/

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