JSON with PHP tutorial

In this tutorial learn how to json encode and json decode with php  tutorial example - programming technology world

Encoding JSON in PHP (json_encode())


PHP json_encode() function is used for encoding JSON in PHP. This function returns the JSON representation of a value on success or FALSE on failure.


Syntax

string json_encode ( $value [, $options = 0 ] )
Example


<?php
   $arr = array('id' => 1, 'name' => "Nakiya", 'age' => 20, 'address' => "USA");
   echo json_encode($arr);
?>

Above tutorial OUTPUT :


{"id":1,"name":"Nakiya","age":20,"address":"USA"}

Decoding JSON in PHP (json_decode())

PHP json_decode() function is used for decoding JSON in PHP. This function returns the value decoded from json to appropriate PHP type result.

syntax

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

When TRUE, returned objects will be converted into associative arrays.


<?php
   
   $json='{"id":1,"name":"Nakiya","age":20,"address":"USA"}';
   
   var_dump(json_decode($json));
   var_dump(json_decode($json, true));

?>
Above Example output


object(stdClass)#1 (4) {
  ["id"]=>
  int(1)
  ["name"]=>
  string(6) "Nakiya"
  ["age"]=>
  int(20)
  ["address"]=>
  string(3) "USA"
}
array(4) {
  ["id"]=>
  int(1)
  ["name"]=>
  string(6) "Nakiya"
  ["age"]=>
  int(20)
  ["address"]=>
  string(3) "USA"
}

No comments:

Post a Comment

how to call ssh from vs code

 To call SSH from VS Code, you can use the built-in Remote Development extension. This extension allows you to open a remote folder or works...