😁PHP JSON full (ok)

https://zetcode.com/php/json/

PHP JSON encode

C:\xampp\htdocs\abc\encode.php

<?php
$data = ["falcon", "sky", "cloud", "orange", "wood", "forest"];
header('Content-type:application/json;charset=utf-8');
echo json_encode($data);

PHP JSON decode

C:\xampp\htdocs\abc\decode.php

<?php
$data = '{
  "name": "John Doe",
  "occupation": "gardener"
}';
$a = json_decode($data, true);
header('Content-type:text/html;charset=utf-8');
echo "{$a["name"]} is a {$a["occupation"]}";
$ php -S localhost:8000 decode.php

We start the server.

$ curl localhost:8000
John Doe is a gardener

PHP JSON read from file

C:\xampp\htdocs\abc\data.json

[
  {"name": "John Doe", "occupation": "gardener", "country": "USA"},
  {"name": "Richard Roe", "occupation": "driver", "country": "UK"},
  {"name": "Sibel Schumacher", "occupation": "architect", "country": "Germany"},
  {"name": "Manuella Navarro", "occupation": "teacher", "country": "Spain"},
  {"name": "Thomas Dawn", "occupation": "teacher", "country": "New Zealand"},
  {"name": "Morris Holmes", "occupation": "programmer", "country": "Ireland"}
]
<?php
$filename = 'http://localhost/abc/data.json';
$data = file_get_contents($filename);
$users = json_decode($data);
?>
<html>
	<table>
		<tbody>
			<tr>
				<th>Name</th>
				<th>Occupation</th>
				<th>Country</th>
			</tr>
			<?php foreach ($users as $user) { ?>
			<tr>
				<td>
					<?= $user->name; ?>
				</td>
				<td>
					<?= $user->occupation; ?>
				</td>
				<td>
					<?= $user->country; ?>
				</td>
			</tr>
			<?php } ?>
		</tbody>
	</table>
</html>

PHP JSON and JS fetch API

C:\xampp\htdocs\abc\index.php

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Home page</title>
    <style>
      th,
      td {
        font: 15px 'Segoe UI';
      }
      table,
      th,
      td {
        border: solid 1px #ddd;
        border-collapse: collapse;
        padding: 2px 3px;
        text-align: center;
      }
      tr:nth-child(odd) {
        background: #efefef
      }
      th {
        font-weight: bold;
      }
    </style>
  </head>
  <body>
    <button id="getData">Get data</button>
    <br>
    <br>
    <div id="output"></div>
    <script>
      const getBtn = document.getElementById('getData');
      const output = document.getElementById('output');
      const table = document.getElementById('table');
      getBtn.addEventListener('click', () => {
        fetch('http://localhost/abc/data.php').then((res) => {
          return res.json();
        }).then((data) => {
          output.innerHTML = '';
          let table = createTableAndHeader();
          output.appendChild(table);
          appendRows(table, data);
        }).catch((err) => {
          console.log("error fetching data");
          console.log(err);
        })
      });
      function createTableAndHeader() {
        let table = document.createElement("table");
        let tr = table.insertRow(-1);
        let headers = ["Name", "Occupation", "Country"];
        for (let i = 0; i < 3; i++) {
          let th = document.createElement("th");
          th.innerHTML = headers[i];
          tr.appendChild(th);
        }
        return table;
      }
      function appendRows(table, data) {
        for (let i = 0; i < data.length; i++) {
          let tr = table.insertRow(-1);
          for (const [_, value] of Object.entries(data[i])) {
            let cell = tr.insertCell(-1);
            cell.innerHTML = value;
          }
        }
      }
    </script>
  </body>
</html>

Last updated