Cain Nuke Cain Nuke - 1 month ago 8
JSON Question

want to read data from a json onto a php file

I have the following json data:

{"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}}

]}


I want to get that data and parse it as html like this:

<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>


I tried writing this code:

$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);


but from here on I am stuck and I cant figure out whats next. Help please?

Thank you.

Answer

JSON isn't HTML. This is way you shouldn't treat it as such (e.g. not calling $dom->loadHTML($data);

PHP is a great templating language, which allows for quick generation of HTML. In your specific case, I would do something like this:

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

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

If you do this. Be sure to escape the input strings to protect yourself against XSS attacks using htmlspecialchars().

Note: This approach doesn't "scale" very well, if you want to do this with many different html templates. There are dedicated HTML template engines for PHP floating around the web, Twig is a very popular one for example.

Comments