トップへ(mam-mam.net/)

How to Handle JSON in PHP|Using json_encode and json_decode Safely and Effectively

Japanese

Encoding and Decoding JSON Strings in PHP (json_encode / json_decode)

This page introduces how to work with JSON data in PHP.
Here, we explain the basic usage of json_encode and json_decode with practical examples, showing how to convert arrays and objects to and from JSON.
The content is simple and practical, ideal for anyone who wants to review the syntax and usage.

To convert an associative array or object into a JSON string,
use the json_encode function.

To convert a JSON string back into an associative array or object,
use the json_decode function.
Sample source code is shown below.

Convert an Associative Array to a JSON String (Encoding)

Running the following source code:

<?php
  $a = [];
  $a["a"] = "1";
  $a["b"][0] = "2";
  $a["b"][1] = "2";
  echo json_encode($a);
?>

Produces the following output:

{"a":"1","b":["2","2"]}

Decoding a JSON String into an Associative Array

To decode a JSON string into an associative array, pass true as the second argument.
json_decode(JSON_string, true)

Running the following code:

<?php
  $arr = json_decode('{ "a":"Hello", "b":[41, "String"] }', true);
  var_dump($arr);
  echo PHP_EOL;
  echo $arr["b"][0]; // Output the value of ["b"][0]
?>

Outputs the following:

array(2) {
  ["a"]=>
  string(5) "Hello"
  ["b"]=>
  array(2) {
    [0]=>
    int(41)
    [1]=>
    string(6) "String"
  }
}

41

Decode a JSON String into an Object

To decode a JSON string into an object, pass false as the second argument.
json_decode(JSON_string, false)
If the second argument is omitted, the value defaults to false, and the JSON string is converted into an object.

Running the following code:

<?php
  $obj = json_decode('{ "a":"Hello" , "b":[41, "String"] }', false);
  var_dump($obj);
  echo PHP_EOL;
  echo $obj->b[0]; // Output the value of b[0]
?>

Produces the following output:

object(stdClass)#2 (2) {
  ["a"]=>
  string(5) "Hello"
  ["b"]=>
  array(2) {
    [0]=>
    int(41)
    [1]=>
    string(6) "String"
  }
}

41

PHP | Samples