PHP json_encode Function | JSON Representation of Value

The PHP json_encode is an inbuilt Function in PHP that returns a JSON representation of the input value. For example, it can create a convert a PHP array to JSON String. In this article, we will discuss the PHP json_encode Function. Also, we will discuss a few examples of using it.

Also, in order to convert a JSON String back to a PHP Object, you can use the PHP json_decode Function.

Syntax

json_encode($value, $options, $depth);

Parameters

The PHP json_encode Function expects one mandatory and two optional parameters. The description of the parameters is given below as follows:

  • $value: We need to pass the mandatory value which we need to encode to JSON. Also, it can be of any data type (string, integer, array, object etc) except a resource.
  • $options: You can also pass optional bitmasking options to the function. The behavior of the constants is defined on JSON Constants Page.
  • $depth: You can also optionally set the maximum depth. However, it must be greater than 0. The default value to this parameter is 512.

Return Value

The PHP json_encode Function returns the encoded JSON String. However, it returns false on failure.

PHP json_encode Function

Examples

Example 1: Simple String/Integer to JSON

You can convert a simple string/integer value to a JSON string using the function as follows:

<?php
	
	$value = 'Concatly - Bringing Knowledge Together';
	echo json_encode($value);
	/* "Concatly - Bringing Knowledge Together" */

	$integerValue = 10;
	echo json_encode($integerValue);
	/* 10 */

?>

Example 2: PHP Array to JSON

You can also convert a PHP array to JSON string as follows:

<?php
  
  $testArray = array(
    'Users' => array(
      array('First' => 'Chandler', 'Last' => 'Bing'),
      array('First' => 'Rachael', 'Last' => 'Green'),
      array('First' => 'Ross', 'Last' => 'Geller')
    )
  );
  echo json_encode($testArray);
?>

The above code snippet will print the following JSON:

{
"Users": [{
"First": "Chandler",
"Last": "Bing"
},
{
"First": "Rachael",
"Last": "Green"
},
{
"First": "Ross",
"Last": "Geller"
}
]
}

Example 3: PHP Class Objects to JSON

Similarly, you can convert Class Object to JSON.

<?php
  class User {
    public $name;
    public $age;
  }
  $user = new User();
  $user->name = 'Chandler';
  $user->age = 26;
  echo json_encode($user);
?>
{"name":"Chandler","age":26}

Conclusion

In this article, we discussed the PHP json_encode Function. It is used to convert a value to JSON String. You can use the PHP json_decode Function to convert a JSON String back to the corresponding value.

Read more about json_encode on PHP Official Documentation.

Spread the Knowledge

Leave a Reply

Your email address will not be published. Required fields are marked *