PHP | json_encode() Function (original) (raw)

Last Updated : 17 Jun, 2019

The json_encode() function is an inbuilt function in PHP which is used to convert PHP array or object into JSON representation.Syntax :

string json_encode( value,value, value,option, $depth )

Parameters:

Return Value: This function returns a JSON representation on success or false on failure.Example 1: This example encodes PHP array into JSON representation.

PHP `

"GFG", "email"=>"abc@gfg.com"); // Use json_encode() function json=jsonencode(json = json_encode(json=jsonencode(value); // Display the output echo($json); ?>

`

Output:

{"name":"GFG","email":"abc@gfg.com"}

Example 2: This example encodes PHP multidimensional array into JSON representation.

PHP `

"GFG", array( "email"=>"abc@gfg.com", "mobile"=>"XXXXXXXXXX" ) ); // Use json_encode() function json=jsonencode(json = json_encode(json=jsonencode(value); // Display the output echo($json); ?>

`

Output:

{"name":"GFG","0":{"email":"abc@gfg.com","mobile":"XXXXXXXXXX"}}

Example 3: This example encodes PHP objects into JSON representation.

PHP `

organisation = "GeeksforGeeks"; $value->email = "feedback@geeksforgeeks.org"; // Use json_encode() function json=jsonencode(json = json_encode(json=jsonencode(value); // Display the output echo($json); ?>

`

Output:

{"organisation":"GeeksforGeeks","email":"feedback@geeksforgeeks.org"}

Reference: https://www.php.net/manual/en/function.json-encode.php