There are many cases when you need to parse JSON data format or to encode one. Examples are numerous: dealing with local config files, remote API requests or responses, structured data files, etc. To deal with JSON in PHP you need only two functions: json_decode and json_encode.

Assume we have a JSON-formatted config file config.json

    "server" : "localhost",
    "port" : 18435,
    "database" : "blog",
    "user" : "sam"

The example of reading and parsing this config file in PHP script:

$json = file_get_contents(__DIR__ . '/../config/config.json');
$config = json_decode($json);

echo 'Database name is ' . $config->database;

By default, json_decode will return an instance of stdClass. To get an associative array insted you should pass true into json_decode as a second argument:

$json = file_get_contents(__DIR__ . '/../config/config.json');
$config = json_decode($jsonm, true);

echo 'Database name is ' . $config['database'];

To encode a JSON string from a given associative array or an instance of stdClass you should use json_encode function:

$config =
    'server'   => 'localhost',
    'port'     => 18435,
    'database' => 'blog',
    'user'     => 'sam'

$json = json_encode($config);

echo $json; # Prints JSON representation of $config array

There are several useful options we should learn at this lesson which you can pass into the second argument of json_encode:

JSON_PRETTY_PRINT      # Encode a JSON with convenient human-readable indention
JSON_NUMERIC_CHECK     # Encode numeric strings as numbers
JSON_UNESCAPED_SLASHES # Do not escape slashes
JSON_UNESCAPED_UNICODE # Do not encode Unicode characters with escape sequence

These options can be combined using bitwise or operator:

$json = json_encode($config, JSON_NUMERIC_CHECK | JSON_UNESCAPED_UNICODE);
Rate this post:
Lesson 15
Lesson 17
Share this page:

Learning plan

How to split PHP script into pieces and include them into each other
14. Operators
We should learn all PHP operators in details before we could continue
15. stdClass
The very basics of stdClass PHP class
16. JSON
How to work with JSON in PHP
17. YAML
How to work with YAML in PHP
Some additional functions you should learn to work with PHP strings