×

php · level 2 · unit 5 · lesson 4

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

turns an array into text you can save or send.

A file holds only text, so how do you save an array? Turn it into JSON, a plain text way of writing data that nearly every language understands. gives text like {"name":"Rex","age":4}.

turns it back. The true asks for arrays. Leave it out and you get an object instead, which square brackets cannot open. Broken JSON gives back null.

Pass JSON_PRETTY_PRINT to json_encode and the text is spread over lines, easier for people to read.

<?php
$path = sys_get_temp_dir() . "/pet.json";
$pet = ["name" => "Rex", "age" => 4, "tricks" => ["sit", "roll"]];
file_put_contents($path, json_encode($pet));
echo file_get_contents($path) . "\n";
$loaded = json_decode(file_get_contents($path), true);
echo "{$loaded["name"]} knows " . count($loaded["tricks"]) . " tricks\n";

JSON is also how most websites and apps send data to each other, so you will meet it everywhere.