Want some programming help? [close]

Working with JSON in PHP

Introduction

This guide will show you how to perform basic conversion between PHP objects and JSON strings.

Dump PHP object to JSON with json_encode

If you have a PHP object like an array and you need to "export" the value as a string, you can use json_encode().

Common examples for this are:

  • Converting an array to a JSON string to return over a REST API
  • To save an object to disk in JSON format

Definition:

# Definition
json_encode (mixed $value [,int $options=0 [,int $depth=512]]): string

Example:

<?php
$json_string = json_encode(['my_key' => 'my value', 'other_key' => 'other value']);
echo $json_string;

Example output:

{"my_key":"my value","other_key":"other value"}

Convert JSON string to PHP object with json_decode

When you have a JSON string and you need to work with it as a PHP object or array, you can use json_decode(). It will let you create a plain-old PHP object (POPO) or an associative array.

A common example is when you receive a REST API response from a web service or when you load a JSON file from disk.

Definition:

# Definition
json_decode(string $json [,bool $assoc=FALSE [,int $depth=512 [,int $options= 0]]]): mixed

Example:

<?php
$json_string = '{"my_key":"my value","other_key":"other value"}';
$my_array =  json_decode($json_string);
print_r($my_array)

Example output:

stdClass Object ( [my_key] => my value [other_key] => other value ) 

Reading and writing to file

You can quickly read and write data to files with file_put_contents() and file_get_contents().

// Store a PHP object as a JSON string
file_put_contents('test.json', json_encode([2, 4, 6]));

// Read JSON string in to a PHP object
$my_array = json_decode(file_get_contents('test.json'));
print_r($my_array);

To learn more about files and directories in PHP check out my tutorial, Working with Files and Directories with PHP.

Conclusion

After reading this you should understand how to perform basic conversion between PHP objects and JSON strings.

References

Advertisement