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

# PHP JSON full (ok)

### PHP JSON encode

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

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

{% embed url="http://localhost/abc/encode.php" %}

<figure><img src="https://3988971916-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-LXUV09EJOZ8BKB8YL5I%2Fuploads%2FRIqhruFw9Sama8ufRJ34%2FScreenshot_2.png?alt=media&#x26;token=2177bc9a-48bf-4e7f-954f-b69fac70040d" alt=""><figcaption></figcaption></figure>

### PHP JSON decode

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

```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

<figure><img src="https://3988971916-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-LXUV09EJOZ8BKB8YL5I%2Fuploads%2FlOi47pIspgQhYnDabkdK%2FScreenshot_3.png?alt=media&#x26;token=36e75fdb-09a7-4032-9194-00a05ebfc7b7" alt=""><figcaption></figcaption></figure>

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"}
]
```

{% embed url="http://localhost/abc/readjson.php" %}

```php
<?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

```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>
```

