JSON Tutorials
- What is Json
- Json Example
- Json Object Example
- Json with php
- How to Convert Data from MySQL to JSON using PHP
- How to store json Data into MySQL database using PHP
- How to insert json data into mysql database using PHP
- validate json string in php
- Json with AJAX
- Json with javascript
- Json Program example
Important Links
JSON
In php, there are two types of function which allows us to encode and decode JSON.
1) PHP json_encode
The json_encode() function returns the JSON representation of a value. In other words, it converts PHP variable (containing array) into JSON. This function returns the JSON representation of a value on success or FALSE on failure.
Array data converted into Json format
Example
<?php
$arr = array(
'a' => 1,
'b' => 2,
'c' => 3,
'd' => 4,
'e' => 5
);
echo json_encode($arr);
?>
output
File name : index.php
<?php
$arr2 = array('firstName' => 'mahtab', 'lastName' => 'habib', 'email' => 'mahtab@gmail.com');
echo json_encode($arr2);
?>
Example
File name :
File name :
File name :
2) PHP json_decode
The json_decode() function decodes the JSON string into an array. In other words, it converts JSON string into a PHP variable. This function returns object by default.
File name : index.php
<?php
$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
var_dump(json_decode($json, true));//true means returned object will be converted into associative array
?>
Output :-
["a"] => int(1)
["b"] => int(2)
["c"] => int(3)
["d"] => int(4)
["e"] => int(5)
}
Example :-
File name : index.php
<?php
$json2 = '{"firstName" : "mahtab", "lastName" : "habib", "email" : "mahtab@gmail.com"}';
var_dump(json_decode($json2, true));
?>
Output :-
["firstName"]=> string(6) "mahtab"
["lastName"]=> string(5) "habib"
["email"]=> string(16) "mahtab@gmail.com"
}
Json data converted into array
File name : index.php
<?php
$result = '[
{"name": "mahtab", "occupation": "developer", "country": "India"},
{"name": "Sana", "occupation": "Student", "country": "India"},
{"name": "Mahira", "occupation": "architect", "country": "Pakistan"},
{"name": "Habib", "occupation": "Doctor", "country": "Dubai"}
]';
$data = json_decode($result);
print_r($data);
foreach($data as $row){
echo $row->name;
}
?>
Output :-
example
File name :
<?php
$data = '{
"name": "sana mahtab",
"occupation": "Doctor"
}';
$a = json_decode($data, true);
header('Content-type:text/html;charset=utf-8');
echo "{$a["name"]} is a {$a["occupation"]}";
json data read from file
File name : data.json
<?php
$filename = 'data.json';
$data = file_get_contents($filename);
$users = json_decode($data);
?>
<html>
<table>
<tbody>
<tr>
<th>Name</th>
<th>Occupation</th>
<th>Country</th>
</tr>
<?php foreach ($users as $user) { ?>
<tr>
<td> <?= $user->name; ?> </td>
<td> <?= $user->occupation; ?> </td>
<td> <?= $user->country; ?> </td>
</tr>
<?php } ?>
</tbody>
</table>
</html>
json read from database
File name :
<?php
$db = new SQLite3('test.db');
$res = $db->query('SELECT * FROM cities');
$cities = [];
while ($row = $res->fetchArray()) {
$cities[] = $row;
}
header('Content-type:application/json;charset=utf-8');
echo json_encode(['cities' => $cities]);
get data from api using curl
File name :
function get_json_data_api()
{
$url = 'https://ittutorial.in/data/Report?home=data';
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($curl);
curl_close($curl);
// print_r($result);
// $data_arr = json_decode($result, true);
// $data_arr = json_decode($result, JSON_INVALID_UTF8_IGNORE);
// print_r($data_arr);
}
converting JSON to array in PHP we use JSON decode json_decode() function
File name :
// JSON string
$data_json = '[{"first_name":"mahtab","gender":"male"},{"first_name":"sana","gender":"female"},{"first_name":"sara","gender":"female"}]';
// Convert JSON string to Array
$result = json_decode($data_json , true); // it returned objects will be converted into associative arrays.
echo "<pre>";
print_r($result );
echo $result [0]["first_name"];
File name :
// JSON string
$data_json = '[{"first_name":"mahtab","gender":"male"},{"first_name":"sana","gender":"female"},{"first_name":"sara","gender":"female"}]';
// Convert JSON string to Array
$result = json_decode($data_json);// will convert your json object into an array
echo "<pre>";
print_r($result );
echo $result [0]->first_name;
Note :-
File name :
Optional parameters :- (JSON_BIGINT_AS_STRING, JSON_INVALID_UTF8_IGNORE, JSON_INVALID_UTF8_SUBSTITUTE, JSON_OBJECT_AS_ARRAY, JSON_THROW_ON_ERROR)
Note :-
File name :
$data = 's:59:"[{"item_id":"abc","qty":4,"points":"12"}]"';
print_r(json_decode(unserialize($data),true));
$data = 's:109:"[{"item_id":"def","qty":3,"points":"10"},{"item_id":"grh","qty":7,"points":"12"}]"';
print_r(json_decode(unserialize($data),true));
Json error Example
json_last_error()
File name :
<?php
// An invalid json string
$string = "{'sana':2,'mahtab':37,'Nusrat':36}";
echo "Decoding: " . $string;
json_decode($string);
echo "<br>Error: ";
switch (json_last_error()) {
case JSON_ERROR_NONE:
echo "No errors";
break;
case JSON_ERROR_DEPTH:
echo "Maximum stack depth exceeded";
break;
case JSON_ERROR_STATE_MISMATCH:
echo "Invalid or malformed JSON";
break;
case JSON_ERROR_CTRL_CHAR:
echo "Control character error";
break;
case JSON_ERROR_SYNTAX:
echo "Syntax error";
break;
case JSON_ERROR_UTF8:
echo "Malformed UTF-8 characters";
break;
default:
echo "Unknown error";
break;
}
?>
json_last_error_msg()
this function json_last_error_msg() return an error string of last json_encode() or json_decode() call.
The json_last_error_msg() function can return an error message on success, "No Error" if no error has occurred, or false on failure. This function doesn't have any parameters.
File name :
<?php
$json = '{"name": "sana", "age": 2 }';
$decode = json_decode($json, true);
$last_error = json_last_error_msg();
if(strtolower($last_error) != "No Error") {
echo "ERROR: " . $last_error; die;
}
?>
json_last_error()
File name :
<?php
$json = '{"name":"sana","hobbies":{"musics":"Y","play":"Y"]}';
print("\nInput: ".$json."\n");
$array = json_decode($json,true);
if(json_last_error() == JSON_ERROR_NONE) {
print("\nOutput Array:\n");
print(" Type: " . gettype($array) . "\n");
print(" Size: " . count($array) . "\n");
print(" ['name']: " . $array["site"] . "\n");
print(" ['hobbies']['JSON']: " . $array["hobbies"]["JSON"] . "\n");
print("\n Output Array Dump:\n");
var_dump($array);
} else {
print("\n json_decode() error: " . json_last_error_msg(). "\n");
}
?>