Current Location: Home> Latest Articles> Detailed Guide on Converting JSON to Array or Object in PHP

Detailed Guide on Converting JSON to Array or Object in PHP

gitbox 2025-08-04

Introduction to JSON

JSON (JavaScript Object Notation) is a lightweight data interchange format widely used in web development. It is based on JavaScript object notation, making it easy to handle and transmit data across different programming languages.

Converting JSON String to Array

PHP offers the json_decode function to convert JSON strings into PHP arrays. Simply set the second parameter to true to get an array.

$json_string = '{"name": "John", "age": 30, "city": "New York"}';
$data = json_decode($json_string, true);
print_r($data);

Output result:

Array
(
    [name] => John
    [age] => 30
    [city] => New York
)

Converting JSON String to Object

If you want to convert a JSON string into a PHP object, you can omit the second parameter of json_decode, which returns an object by default.

$json_string = '{"name": "John", "age": 30, "city": "New York"}';
$data = json_decode($json_string);
echo $data->name; // Outputs John

Reading JSON Data from a File

When JSON data is stored in a file, you can read it first with file_get_contents, then decode it with json_decode.

$json_string = file_get_contents('data.json');
$data = json_decode($json_string, true);

Encoding PHP Arrays or Objects to JSON String

PHP provides the json_encode function to convert arrays or objects to JSON strings, which is useful for data transmission or storage.

$data = array(
    'name' => 'John',
    'age' => 30,
    'city' => 'New York'
);
$json_string = json_encode($data);
echo $json_string; // Outputs: {"name":"John","age":30,"city":"New York"}

Handling Unicode Characters in JSON Encoding

By default, json_encode escapes Unicode characters. Using the JSON_UNESCAPED_UNICODE option preserves Unicode characters, making it easier to display Chinese and other characters.

$data = array(
    'name' => '张三',
    'age' => 30,
    'city' => '北京'
);
$json_string = json_encode($data, JSON_UNESCAPED_UNICODE);
echo $json_string; // Outputs: {"name":"张三","age":30,"city":"北京"}

Summary

In PHP, the json_decode and json_encode functions make it easy to convert between JSON and arrays or objects. They support reading data from files and handling Unicode characters, greatly simplifying JSON data manipulation in web applications.