Cain Nuke Cain Nuke - 3 years ago 128
JSON Question

want to read data from a json onto a php file

I have the following json data:


"meta":{"type":"TEXT","author":{"nickname":"Gayge","image":{"url":"","height":100,"width":100},"Category":"REGULAR"},"createdAt":1477065361,"details":{"Text":"this is just a test"},"tags":[],"Stats":{"upVoteCount":0,"replyCount":0}},

"meta":{"type":"TEXT","author":{"nickname":"jorf","image":{"url":"","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=""> <b>Gayge</b></span>
<li id="33b">
<p>yet another test</p>
<span>BY:<img src=""> <b>jorf</b></span>

I tried writing this code:

$str = file_get_contents("");
$data = json_decode($str,true);
$dom = new DOMDocument;
$lis = $dom->getElementsByTagName('li');
foreach ($lis as $li) {
$final = $dom->saveHTML();
echo $final;

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

Thank you.

Answer Source

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("");
$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 -->
<? } ?>

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download