我正在与一家慈善机构合作,他们需要自己特定的CMS来发布博客。我已经设置了QuillJS,它运行良好,输出的是JSON。
我如何将JSON数据转换回带有相关标签的HTML?我需要HTML标签也被显示出来,如''。<p>Hello</p>
'. 我可以通过php mysql获取JSON数据,但不知道如何显示标签。
例如,我如何转换以下内容
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"
}
至
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>
预先非常感谢您的帮助
这里有一个完整的解决方案。每一步都会在注释中提到。
<?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;
}
演示。http:/sandbox.onlinephpfunctions.comcodeab862de1113d8744bc2d9463f7a7df2496491110。
所以你需要先对JSON进行解码,这样php就可以把它作为一个数组,然后通过foreach循环显示。
$someJSON = '{
"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"
}';
现在我们解码并显示
$someData = json_decode($someJSON, true);
//--> Create an empty variable to hold the display text...
$output = null;
//--> Run foreach loop, we can see the associative keys in the array, this gives
//--> us everything we need to pull the data out and display it properly...
//--> loop through the converted arrays first child 'blocks' and get the values
foreach ($someData['blocks'] as $value) {
//--> If the 'type' === 'header' wrap value -> ['data'] -> ['text'] in <h2> tag
if($value['type'] === "header"){
$output .= '<h2>'.$value['data']['text'].'</h2>';
}
//--> If the 'type' === 'paragraph' wrap value -> ['data'] -> ['text'] in <p> tag
if($value['type'] === "paragraph"){
$output .= '<p>'.$value['data']['text'].'</p>';
}
}
在你的HTML输出中,在php标签内显示变量的连贯HTML,在 $output
<html>
<div id="my_id">
<span class="my_class">
<?=$output?> or <?php echo $output; ?>
</span>
</div>
</html>
http:/sandbox.onlinephpfunctions.comcodee8fdb5b84af5346d640e92e6788e5c2836b9ad07。