想要从json读取数据到php文件

时间:2016-10-22 13:33:56

标签: php json

我有以下json数据:

{"total":{"count":68},"Messages":[

{"messageId":"32b","replyId":"b2744",
"meta":{"type":"TEXT","author":{"nickname":"Gayge","image":{"url":"https://sas.com/16.jpg","height":100,"width":100},"Category":"REGULAR"},"createdAt":1477065361,"details":{"Text":"this is just a test"},"tags":[],"Stats":{"upVoteCount":0,"replyCount":0}},

{"messageId":"33b","replyId":"b3744",
"meta":{"type":"TEXT","author":{"nickname":"jorf","image":{"url":"https://sas.com/17.jpg","height":100,"width":100},"Category":"REGULAR"},"createdAt":1477065361,"details":{"Text":"yet another test"},"tags":[],"Stats":{"upVoteCount":0,"replyCount":0}}

]}

我想获取该数据并将其解析为html:

<li id="32b">
 <p>this is just a test</p>
 <span>BY:<img src="https://sas.com/16.jpg"> <b>Gayge</b></span>
</li>
<li id="33b">
 <p>yet another test</p>
 <span>BY:<img src="https://sas.com/17.jpg"> <b>jorf</b></span>
</li>  

我尝试编写此代码:

$str = file_get_contents("https://mypage.net/json.txt");
$data = json_decode($str,true);
$dom = new DOMDocument;
$dom->loadHTML($data);
$lis = $dom->getElementsByTagName('li');
 foreach ($lis as $li) {
     $li->appendChild($p);
     $li->appendChild($span);
 }
 $final = $dom->saveHTML();
 echo $final;
fclose($open_file);

但是从这里开始我被卡住了,我无法弄清楚接下来会发生什么。请帮忙吗?

谢谢。

1 个答案:

答案 0 :(得分:0)

JSON不是HTML。这是你不应该这样对待的方式(例如不要叫$dom->loadHTML($data);

PHP是一种很棒的模板语言,可以快速生成HTML。在你的具体情况下,我会做这样的事情:

$str = file_get_contents("https://mypage.net/json.txt");
$data = json_decode($str,true);

foreach ($data['Messages'] as $msg) {
?>
    <li id="<?= htmlspecialchars($msg['messageId']); ?>">
    <p> <?=htmlspecialchars($msg['meta']['details']['Text']); ?></p>
    <!-- The rest of your template goes here -->
    </li>
<? } ?>

如果你这样做。请务必使用XSS attacks转义输入字符串以防止htmlspecialchars()。{/ p>

注意:这种方法不会缩放&#34;很好,如果你想用许多不同的html模板做到这一点。 PHP上有专门的HTML模板引擎,例如Twig非常受欢迎。