How to parse a JSON string
Short answer
json_decode() with true as the second argument returns an array:
<?php
$user = json_decode('{"name": "Anna", "tags": ["php", "sql"]}', true);
echo $user['name'], ' ', count($user['tags']);Output:
Anna 2Invalid JSON
With the JSON_THROW_ON_ERROR flag a failure becomes an exception:
<?php
try {
json_decode('{broken', true, 512, JSON_THROW_ON_ERROR);
} catch (JsonException $error) {
echo 'Invalid JSON';
}Output:
Invalid JSONFrom a file
Read the file and parse its content:
<?php
$file = sys_get_temp_dir() . '/recipe-config.json';
file_put_contents($file, '{"theme": "dark", "size": 14}');
$config = json_decode(file_get_contents($file), true);
echo $config['theme'];Output:
darkFunctions used in this recipe
- json_decode — Parses a JSON string.
- json_encode — Converts a value to a JSON string.
- file_get_contents — Reads a whole file into a string.