-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

2
  • possible duplicate: Get data from JSON file with PHP. Commented Mar 5, 2015 at 3:25
  • Sorry, my question might be duplicate but the samples from the page you mention is different from my JSON file data structure. Commented Mar 5, 2015 at 3:35

2 Answers 2

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

?>
Sign up to request clarification or add additional context in comments.

Comments

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

?>

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.