PHP如何将HTML字符串保存到数据库中

sai*_*iid 5 php mysql database string html5

为了响应API调用,我得到一个完整的HTML脚本.完全意味着它包括HTML CSS和Javascript.现在我把那个HTML作为PHP变量中的字符串.

$content = '<html>
<head>
  <script>--Some javascript and libraries included--</script>
  <title></title>
</head>
<body>
   <style>--Some Styling--</style>
</body>
</html>';
Run Code Online (Sandbox Code Playgroud)

现在,在数据库中保存此变量的最佳方法是什么?如何?

  • 作为VARCHAR或TEXT类型的字符串?
  • 作为Base64编码VARCHAR或TEXT类型的字符串?
  • 作为BLOB类型的二进制文件?

或者您想建议的任何其他(可能是序列化或打包)?

sai*_*iid 11

我使用base64编码数据以BLOB数据类型存储在我的数据库中.样板代码如下.

$content = '<html>
<head>
  <script>--Some javascript and libraries included--</script>
  <title></title>
</head>
<body>
   <style>--Some Styling--</style>
</body>
</html>';
Run Code Online (Sandbox Code Playgroud)

在base64中编码数据

$encodedContent = base64_encode($content); // This will Encodes
Run Code Online (Sandbox Code Playgroud)

并使用BLOB将数据保存在数据库中.现在在检索数据后,只需将其解码如下.

$ContentDecoded = base64_decode($content);  // decode the base64
Run Code Online (Sandbox Code Playgroud)

现在$ contentDecoded的值是纯HTML.

  • @e4c5 说:你通过这种方式增加存储大小 (2认同)

e4c*_*4c5 6

如果您对其进行 Base64 编码,则会将存储大小增加大约 30%,并且每次显示时都需要对其进行解码。查看Wordpress 的表结构,Wordpress 是使用最广泛的软件,它使用 php 将 html 存储在 mysql 数据库上。他们用什么?长文本。在您的情况下,文本可能更好,因为您可能对页面的大小有一个很好的了解。