G
G
gaki2021-04-29 19:38:27
PHP
gaki, 2021-04-29 19:38:27

How to display data from json to the screen?

Form code that is processed on the main page

<?php
if(isset($_POST["name"]) && isset($_POST["number"])) {
    $fp = fopen('data.json', 'a');
    $arr = ['name' => $_POST['name'], 'number' => $_POST['number']];
    
    $json_data = json_encode($arr).PHP_EOL;

    fwrite($fp, $json_data);
    fclose($fp);

}
?>

Page code where I have to display data from json
<!DOCTYPE html>
<html lang="ru">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Grid</title>
</head>
<body>
    <table>
        <tr>
            <td>Name</td>
            <td>Number</td>
        </tr>
        <?php
        $r_json = file_get_contents("data.json");
        $arr_json = json_decode("data.json", true);
        

        ?>
    </table>
</body>
</html>

data.json code where data is stored
{"name":"1","number":"86"}
{"name":"12","number":"8"}
{"name":"13","number":"6"}
{"name":"dawd","number":"2134"}
{"name":"авф","number":"213"}
{"name":"14","number":"812"}
{"name":"15","number":"823"}
{"name":"16","number":"82"}
{"name":"17","number":"81"}

I would also like to ask .. Is the correct format for the json that I save? Or do I need to redo it somehow? (If redo, then how)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander Toropov, 2021-04-30
@usxr

Is the format correct for the json that I am saving?

No, JSON must have one pair of opening "{" and closing "}" brackets.
Or do I need to redo it somehow? (If redo, then how)

Yes, it will change, something like this:
<?php
$arr = ['name' => $_POST['name'], 'number' => $_POST['number']];

//читаем данные из файла
$r_json = file_get_contents("data.json");
$arr_json = json_decode($r_json, true);

//склеить данные из файла и теми что получили из формы
$result = array_merge($arr_json, $arr);

//сохраняем данные в файл
$fp = fopen('data.json', 'a');
fwrite($fp, $json_data);
fclose($fp);

In general, it’s better to save to the database and then return pure JSON on the page by setting HTTP headers:
header("Content-type: application/json; charset=utf-8");

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question