LogoLoading Please Wait...

The Fundamental Guide to Working With JSON in PHP

By divine_admin_infosys

What is JSON?

JSON is called as Javascript Object Notation. It is used for exchanging data between different servers or website or different server languages like Java, Python, PHP, etc. Here we are going to talk about JSON working with PHP.

How to work with JSON in PHP?

Basically, there are some inbuilt functions which you can use to combine data into JSON format or to get data into a normal form from JSON format.

  • json_encode( )
  • json_decode( )
  • json_last_error( )

This is some basic functions available in PHP which we can use to create web services or we can use to get data from some API.

Syntax

  • string json_encode(mixed value,[int options=0]  
  • mixed json_decode(string json,[bool assoc = false,[int depth=512]]

Example (json_encode())

$array = array("ID"=>"D01","Name"=>"Divine Infosys","City"=>"Ahmedabad");     

echo json_encode($array);

Output : {“ID”:”D01”,”Name”:”Divine Infosys”,”City”:”Ahmedabad}

Example (json_decode())

$json2 = '{"ID":"D01","Name":"Divine Infosys","City":"Ahmedabad"}'; 

var_dump(json_decode($json2, true));

Output

array(3)

{

[“ID”]=> string(6) “D01

[“Name”]=> string(9) “Divine Infosys

[“City”]=> string(10) “Ahmedabad

}

Example (json_last_error())

$error = json_last_error();

var_dump($json, $error === JSON_ERROR_UTF8);



Divine Infosys