QuestionsPHP JSON : json_encode and json_decode
mmkevinsmith0610 asked 2 months ago

PHP allows to encode and decode JSON by the help of json_encode() and json_decode functions.

PHP json_encode

The json_encode() function converts PHP variable (array) into JSON.

Syntax:

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

Example:

<?php

$arr = array(‘a’ => blue, ‘b’ => red, ‘c’ => black, ‘d’ => join, ‘e’ => case);

echo json_encode($arr);

?>

Result:-

{“a”: blue,”b”:red,”c”:black,”d”:join,”e”:case}

PHP json_decode

The json_decode() function converts JSON string into a PHP variable. This is reverse of json_encode function.

Syntax:

mixed json_decode ( string $json [, bool $assoc = false [, int $depth = 512 [, int $options = 0 ]]] )

Example:

$decode =   {“a”: blue,”b”:red,”c”:black,”d”:join,”e”:case}

var_dump(json_decode($decode, true));

Result:-

array(

‘a’ => blue,

‘b’ => red,

‘c’ => black,

‘d’ => join,

‘e’ => case

);

Your Answer
Login
Enter email and password to comment or answer
Not the answer you are looking for? Browse other questions tagged or ask your own question.