Encodera

Thanks for reading!

Donate to the site — we work hard for you.

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 2

Invalid 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 JSON

From 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:

dark

Functions used in this recipe

Thanks for reading!

Donate to the site — we work hard for you.