-2

I'm just stucked with this. How could I read a json file using PHP.

I have file.json with the following data sample


[
    {
        "lastname": "John",
        "firstname": "Michael"
    },
    {
        "lastname": "Nick",
        "firstname": "Bright"
    },
    {
        "lastname": "Cruz",
        "firstname": "Manny"
    }
]

Can you share me a php code how to read file.json and extract it to html table?

<table>
<tr><td>Firstname</td><td>Lastname</td></tr>
</table>

Thank you in advance

Adrian Cid Almaguer
  • 7,815
  • 13
  • 41
  • 63
LayoutPH
  • 399
  • 1
  • 3
  • 16
  • possible duplicate: [Get data from JSON file with PHP](https://stackoverflow.com/questions/19758954/get-data-from-json-file-with-php). – Ryan Vincent Mar 05 '15 at 03:25
  • Sorry, my question might be duplicate but the samples from the page you mention is different from my JSON file data structure. – LayoutPH Mar 05 '15 at 03:35

2 Answers2

1

Check my json because in your code you have an extra comma in the firstname line.

Try this code:

<?php

$json =  '[
    {
        "lastname": "John",
        "firstname": "Michael"
    },
    {
        "lastname": "Nick",
        "firstname": "Bright"
    },
    {
        "lastname": "Cruz",
        "firstname": "Manny"
    }
]';

$obj = json_decode($json, true);

echo '<table>
<tr><td>Firstname</td><td>Lastname</td></tr>';

foreach($obj as $key => $value) {
    echo "<tr><td>{$value['firstname']}</td><td>{$value['lastname']}</td></tr>";
}   

echo '</table>';

?>
Adrian Cid Almaguer
  • 7,815
  • 13
  • 41
  • 63
1

You can decode Json String By json_decode();

<?php 

$jsonStr =  '[
    {
        "lastname": "John",
        "firstname": "Michael"
    },
    {
        "lastname": "Nick",
        "firstname": "Bright"
    },
    {
        "lastname": "Cruz",
        "firstname": "Manny"
    }
]';

$jsonObj = json_decode($jsonStr,true);

var_dump($jsonObj);

?>