I'm working with a charity who need their own specific CMS to post blogs. I have set up QuillJS which works well and output JSON.
How do I convert JSON data back to HTML with the relevant tags? I need the HTML tags to be shown too such as '<p>Hello</p>
'. I can get the JSON data via php mysql but don't know how to show the tags.
For example how to I convert the following
JSON
{
"time" : 1589493865899,
"blocks" : [
{
"type" : "header",
"data" : {
"text" : "Editor.js",
"level" : 2
}
},
{
"type" : "paragraph",
"data" : {
"text" : "Hey. Meet the new Editor. On this page you can see it in action — try to edit this text."
}
}
],
"version" : "2.17.0"
}
To
HTML
<html>
<h2>EditorJS</h2>
<p>Hey. Meet the new Editor. On this page you can see it in action — try to edit this text.</p>
</html>
Many thanks in advance for any help!
Here's a complete solution. Each step is mentioned in the comments:
<?php
$jsonData = '{
"time" : 1589493865899,
"blocks" : [
{
"type" : "header",
"data" : {
"text" : "Editor.js",
"level" : 2
}
},
{
"type" : "paragraph",
"data" : {
"text" : "Hey. Meet the new Editor. On this page you can see it in action — try to edit this text."
}
}
],
"version" : "2.17.0"
}';
//decode the JSON
$data = json_decode($jsonData);
//loop through the blocks
foreach ($data->blocks as $block)
{
$start = "";
$end = "";
//detect the element type and set the HTML tag string
switch ($block->type)
{
case "header":
$start = "<h2>";
$end = "</h2>";
break;
case "paragraph":
$start = "<p>";
$end = "</p>";
break;
}
//output the final HTML for that block
echo $start.$block->data->text.$end;
}
Demo: http://sandbox.onlinephpfunctions.com/code/ab862de1113d8744bc2d9463f7a7df2496491110