Skip to content Skip to sidebar Skip to footer

Using Js and Php to Read and Append to a Json File

PHP JSON

last modified July 26, 2020

PHP JSON tutorial shows how to work with JSON in PHP.

JSON

JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is easily read and written by humans and parsed and generated by machines. The application/json is the official Cyberspace media type for JSON. The JSON filename extension is .json.

The json_encode function returns the JSON representation of the given value. The json_decode takes a JSON encoded string and converts it into a PHP variable.

PHP frameworks such as Symfony and Laravel accept built-in methods that piece of work with JSON.

PHP JSON encode

In the post-obit example, we use the json_encode function.

encode.php

<?php  $data = ["falcon", "heaven", "deject", "orange", "wood", "forest"];  header('Content-blazon:awarding/json;charset=utf-8'); repeat json_encode($data);        

The instance transforms a PHP array into a JSON cord.

$ php -Due south localhost:8000 encode.php        

We get-go the server and locate to the localhost:8000.

JSON view in Firefox
Figure: JSON view in Firefox

Modern spider web browsers bear witness JSON view for JSON information when they receive an advisable content type in the header of the response.

PHP JSON decode

In the following example, nosotros employ the json_decode function.

decode.php

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

The example transforms a JSON string into a PHP variable.

$ php -S localhost:8000 decode.php        

We start the server.

$ curl localhost:8000 John Doe is a gardener        

We send a Become request with curl.

PHP JSON read from file

In the following case, we read JSON data from a file.

information.json

[     {"proper name": "John Doe", "occupation": "gardener", "country": "USA"},     {"proper name": "Richard Roe", "occupation": "driver", "country": "United kingdom"},     {"proper name": "Sibel Schumacher", "occupation": "architect", "land": "Germany"},     {"proper noun": "Manuella Navarro", "occupation": "teacher", "land": "Spain"},     {"proper noun": "Thomas Dawn", "occupation": "teacher", "country": "New Zealand"},     {"proper name": "Morris Holmes", "occupation": "programmer", "country": "Ireland"} ]        

This is the JSON data.

readjson.php

<?php  $filename = 'data.json';  $data = file_get_contents($filename); $users = json_decode($data); ?>  <html> <tabular array>     <tbody>         <tr>             <th>Name</th>             <th>Occupation</thursday>             <th>Country</th>         </tr>         <?php foreach ($users as $user) { ?>         <tr>             <td> <?= $user->name; ?> </td>             <td> <?= $user->occupation; ?> </td>             <td> <?= $user->land; ?> </td>         </tr>         <?php } ?>     </tbody> </tabular array> </html>        

In the code example, we read the file with file_get_contents and decode it into an PHP array with json_decode. Later, we place the data into a table utilizing PHP foreach loop.

PHP JSON read from database

In the following instance, we read information from an SQLite database and render it in JSON.

cities.sql

BEGIN TRANSACTION; DROP TABLE IF EXISTS cities;  CREATE Tabular array cities(id INTEGER PRIMARY Central, proper noun TEXT, population INTEGER); INSERT INTO cities(name, population) VALUES('Bratislava', 432000); INSERT INTO cities(proper noun, population) VALUES('Budapest', 1759000); INSERT INTO cities(proper name, population) VALUES('Prague', 1280000); INSERT INTO cities(name, population) VALUES('Warsaw', 1748000); INSERT INTO cities(name, population) VALUES('Los Angeles', 3971000); INSERT INTO cities(proper noun, population) VALUES('New York', 8550000); INSERT INTO cities(proper name, population) VALUES('Edinburgh', 464000); INSERT INTO cities(proper name, population) VALUES('Berlin', 3671000); COMMIT;        

This SQL lawmaking creates a cities tabular array in SQLite.

$ sqlite3 test.db sqlite> .read cities.sql sqlite> SELECT * FROM cities; 1|Bratislava|432000 2|Budapest|1759000 three|Prague|1280000 4|Warsaw|1748000 five|Los Angeles|3971000 6|New York|8550000 7|Edinburgh|464000 8|Berlin|3671000        

With the sqlite3 command line tool, we generate an SQLite database and create the cities table.

fetch_all.php

<?php  $db = new SQLite3('exam.db'); $res = $db->query('SELECT * FROM cities'); $cities = [];  while ($row = $res->fetchArray()) {     $cities[] = $row; }  header('Content-type:application/json;charset=utf-8'); echo json_encode(['cities' => $cities]);        

In the example, we call up the information from the database and return it as JSON.

PHP JSON and JS fetch API

In the post-obit example, nosotros use JavaScript fetch API to go the JSON data from a PHP script.

data.json

[     {"name": "John Doe", "occupation": "gardener", "country": "United states of america"},     {"proper noun": "Richard Roe", "occupation": "commuter", "land": "United kingdom of great britain and northern ireland"},     {"proper name": "Sibel Schumacher", "occupation": "architect", "land": "Federal republic of germany"},     {"name": "Manuella Navarro", "occupation": "teacher", "country": "Espana"},     {"name": "Thomas Dawn", "occupation": "instructor", "country": "New Zealand"},     {"name": "Morris Holmes", "occupation": "programmer", "state": "Ireland"} ]        

The JSON data is stored in a file.

data.php

<?php  $filename = 'data.json';  $data = file_get_contents($filename); header('Content-type:application/json;charset=utf-viii'); echo $data;        

We read the data and return it to the client.

index.html

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

We accept a push in the document. When nosotros click on the button, the fetch part retrieves JSON data from the data.php script. An HTML table is dynamically congenital and filled with the information.

HTML table filled with JSON data from fetch API
Figure: HTML table filled with JSON data from fetch API

PHP JSON in Slim

In the following instance, we return JSON information from a Slim application.

$ composer req slim/slim $ composer req slim/psr7 $ composer req slim/http        

Nosotros install slim/slim, slim/psr7, and slim/http packages.

public/index.php

<?php  use Psr\Http\Bulletin\ResponseInterface as Response; employ Psr\Http\Message\ServerRequestInterface as Request; use Slim\Factory\AppFactory;  require __DIR__ . '/../vendor/autoload.php';  $app = AppFactory::create();  $app->get('/urban center', function (Request $asking, Response $response): Response {      $cities = [         ["id" => 1, "name" => "Bratislava", "population" => 432000],         ["id" => 2, "proper name" => "Budapest", "population" => 1759000],         ["id" => 3, "name" => "Prague", "population" => 1280000],         ["id" => 4, "proper name" => "Warsaw", "population" => 1748000],         ["id" => 5, "proper name" => "Los Angeles", "population" => 3971000],         ["id" => 6, "proper noun" => "New York", "population" => 8550000],         ["id" => 7, "name" => "Edinburgh", "population" => 464000],         ["id" => 8, "name" => "Berlin", "population" => 3671000],     ];      return $response->withJson(["cities" => $cities]); });  $app->run();        

We use the withJson method of the Response to return JSON data.

PHP JSON in Symfony

In the following instance, we send a JSON response from a Symfony application.

$ symfony new symjson $ cd symjson        

A new application is created.

$ composer req annot $ composer req symfony/orm-pack $ composer req symfony/console        

Nosotros install the annot, symfony/orm-pack, and symfony/console components.

.env

... DATABASE_URL=sqlite:///%kernel.project_dir%/var/ydb.db ...        

We ready up a database URL for the SQLite database.

$ php bin/console doctrine:database:create        

Nosotros create the database.

src/Control/CreateCityTable.php

<?php  namespace App\Command;  use Doctrine\DBAL\Driver\Connection; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputInterface; utilize Symfony\Component\Console\Output\OutputInterface;   class CreateCityTable extends Command {     private $conn;      public function __construct(Connection $conn)     {         $this->conn = $conn;          parent::__construct();     }      protected function configure()     {         $this->setName('app:create-table')             ->setDescription('Creates City tabular array')             ->setHelp('This command creates a Metropolis table');     }      protected function execute(InputInterface $input, OutputInterface $output): int     {         $q1 = "CREATE TABLE cities(id INTEGER Principal KEY, proper name TEXT, population INTEGER)";         $this->conn->executeQuery($q1);          $q2 = "INSERT INTO cities(name, population) VALUES('Bratislava', 432000)";         $this->conn->executeQuery($q2);          $q3 = "INSERT INTO cities(proper name, population) VALUES('Budapest', 1759000)";         $this->conn->executeQuery($q3);          $q4 = "INSERT INTO cities(name, population) VALUES('Prague', 1280000)";         $this->conn->executeQuery($q4);          $q5 = "INSERT INTO cities(name, population) VALUES('Warsaw', 1748000)";         $this->conn->executeQuery($q5);          $q6 = "INSERT INTO cities(proper noun, population) VALUES('Los Angeles', 3971000)";         $this->conn->executeQuery($q6);          $q7 = "INSERT INTO cities(proper name, population) VALUES('New York', 8550000)";         $this->conn->executeQuery($q7);          $q8 = "INSERT INTO cities(name, population) VALUES('Edinburgh', 464000)";         $this->conn->executeQuery($q8);          $q9 = "INSERT INTO cities(proper noun, population) VALUES('Berlin', 3671000)";         $this->conn->executeQuery($q9);          $output->writeln('table successfully created');          render Command::SUCCESS;     } }        

This is a control that creates the cities table in the database.

$ php bin/panel app:create-table        

The command is executed.

src/Repository/CityRepository.php

<?php  namespace App\Repository;  use Doctrine\DBAL\Driver\Connection;  class CityRepository {     protected $conn;      public function __construct(Connection $conn)     {         $this->conn = $conn;     }      public function all(): assortment     {         $queryBuilder = $this->conn->createQueryBuilder();         $queryBuilder->select('*')->from('cities');         $stm = $queryBuilder->execute();          render $stm->fetchAll();     } }        

In the CityRepository, nosotros have the all method which retrieves all rows. We utilise the Doctrine DBAL to execute the database query.

src/Controller/CityController.php

<?php  namespace App\Controller;  employ Symfony\Bundle\FrameworkBundle\Controller\AbstractController; employ Symfony\Component\HttpFoundation\JsonResponse; use Symfony\Component\Routing\Note\Route; use App\Repository\CityRepository;  class CityController extends AbstractController {     /**      * @Route("/metropolis", name="city")      * @param CityRepository $cityRepository      * @return JsonResponse      */     public role alphabetize(CityRepository $cityRepository): JsonResponse     {         $cities = $cityRepository->all();          return $this->json([             'cities' => $cities         ]);     } }        

Within the controller, we fetch all data using the CityRepository. The data transformed into JSON with the json helper.

$ symfony serve        

We offset the web server and locate to the localhost:8000/city.

PHP JSON in Laravel

In the following example, nosotros send a JSON response from a Laravel awarding.

$ laravel new larajson $ cd larajson        

We create a new Laravel application.

.env

... DB_CONNECTION=sqlite DB_DATABASE=/tmp/ydb.db ...        

We define the connection and the database file.

$ affect /tmp/ydb.db        

We create the database file.

$ php artisan brand:migration create_cities_table Created Migration: 2020_07_25_101535_create_cities_table        

A new migration for the cities table is created.

database/migrations/2020_07_25_101535_create_cities_table.php

<?php  use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Back up\Facades\Schema;  class CreateCitiesTable extends Migration {     /**      * Run the migrations.      *      * @return void      */     public function upwardly()     {         Schema::create('cities', function (Pattern $table) {             $table->id();             $table->cord('proper noun');             $table->integer('population');         });     }      /**      * Contrary the migrations.      *      * @return void      */     public function down()     {         Schema::dropIfExists('cities');     } }        

In the migration file, we create a schema for the cities table.

$ php artisan migrate        

We run the migrations.

$ php artisan make:seeder CitySeeder        

We create a information seeder for our database.

database/seeds/CitySeeder.php

<?php  use Illuminate\Database\Seeder;  form CitySeeder extends Seeder {     /**      * Run the database seeds.      *      * @return void      */     public role run()     {         DB::tabular array('cities')->insert([             ['proper name' => 'Bratislava', 'population' => 432000],             ["name" => "Budapest", "population" => 1759000],             ["name" => "Prague", "population" => 1280000],             ["proper name" => "Warsaw", "population" => 1748000],             ["proper noun" => "Los Angeles", "population" => 3971000],             ["name" => "New York", "population" => 8550000],             ["name" => "Edinburgh", "population" => 464000],             ["name" => "Berlin", "population" => 3671000]         ]);     } }        

The seeder inserts 8 rows into the table.

$ php artisan db:seed --class=CitySeeder        

We execute the seeder.

routes/spider web.php

<?php  apply Illuminate\Support\Facades\Road; utilise Illuminate\Http\JsonResponse;  Route::get('/city', function (): JsonResponse {      $cities = DB::table('cities')->get();      render response()->json([         'cities' => $cities     ]); });        

Inside the route, we select all data from the database and return it as JSON with the json helper.

$ php artisan serve        

We run the web server.

$ curl localhost:8000/metropolis {"cities":[{"id":"1","proper noun":"Bratislava","population":"432000"}, {"id":"ii","name":"Budapest","population":"1759000"}, {"id":"three","name":"Prague","population":"1280000"}, {"id":"four","name":"Warsaw","population":"1748000"}, {"id":"5","proper name":"Los Angeles","population":"3971000"}, {"id":"6","name":"New York","population":"8550000"}, {"id":"7","name":"Edinburgh","population":"464000"}, {"id":"8","name":"Berlin","population":"3671000"}]}        

We go the data with the curl tool.

PHP JSON from customer

Symfony provides the HttpClient component which enables us to create HTTP requests in PHP. Nosotros can also send JSON data.

$ composer req symfony/http-customer        

Nosotros install the symfony/http-client component.

send_json_req.php

<?php  require('vendor/autoload.php');  use Symfony\Component\HttpClient\HttpClient;  $httpClient = HttpClient::create(); $response = $httpClient->request('GET', 'http://localhost:8000/greet',  [     'json' => [         'name' => 'Lucia',         'message' => 'Cau'     ] ]);  $content = $response->getContent(); echo $content . "\north";        

The example sends a GET request with a JSON payload.

src/Controller/GreetController.php

<?php  namespace App\Controller;  use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; use Symfony\Component\Routing\Note\Route; use Symfony\Component\HttpFoundation\Response; apply Symfony\Component\HttpFoundation\Request;  class GreetController extends AbstractController {     /**      * @Route("/greet", proper name="greet")      */     public role alphabetize(Request $request): Response     {         $params = [];         if ($information = $request->getContent()) {             $params = json_decode($data, true);         }          $msg = "{$params['name']} says {$params['message']}";          $textResponse = new Response($msg , 200);         $textResponse->headers->set('Content-Type', 'text/plain');          return $textResponse;     } }        

In the GreetController, we process the JSON information and generate a text message, which is returned to the client.

$ php send_json_req.php  Lucia says Cau        

This is the output.

In this tutorial, nosotros have worked with JSON information in plain PHP, Symfony, Slim, and Laravel.

List all PHP tutorials.

penathaterhal.blogspot.com

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

Postar um comentário for "Using Js and Php to Read and Append to a Json File"