Muhammad Saiid Muhammad Saiid - 4 months ago 44
SQL Question

PHP how to save HTML string into database

In response to an API call, I'm getting a full HTML script. Full mean it includes HTML CSS and Javascript. Now I have that HTML as string in PHP variable.

$content = '<html>
<head>
<script>--Some javascript and libraries included--</script>
<title></title>
</head>
<body>
<style>--Some Styling--</style>
</body>
</html>';


Now, what is the best way to save this variable in Database and How?


  • As a string with VARCHAR or TEXT type?

  • As a string with Base64 Encoded with VARCHAR or TEXT type?

  • As a Binary with BLOB type?



Or any other you would like to suggest(May be Serialize or Pack)?

Answer

I use base64 encoded data to store in my Database with the BLOB datatype. The boilerplate code is as follow.

$content = '<html>
<head>
  <script>--Some javascript and libraries included--</script>
  <title></title>
</head>
<body>
   <style>--Some Styling--</style>
</body>
</html>';

To encode data in base64

$encodedContent = base64_encode($content); // This will Encodes

And save the data in database with BLOB. Now after retrieve data, just decode it as follow.

$ContentDecoded = base64_decode($content);  // decode the base64

Now the value of $contentDecoded is the plain HTML.