December 08, 2024
How to merge two json file with PHP
We can merge two json files which has same json structure. In our example we will create two json file and we will merge those with the help of PHP code.
So in current folder lets create our sample json files first. We will keep json file names as json_1.json and json_2.json. Both json files' content mentioned below
json_1.json will contain below json
[{
"name":"John",
"class":"XXI",
"address":"USA"
}]
json_2.json will contain below json
[
{
"name":"Carloss",
"class":"XX",
"address":"CA"
},
{
"name":"Mark",
"class":"VV",
"address":"UK"
}
]
We have below code to merge json_1.json and json_2.json
<?php
$finalArr=$jsonArr1=$jsonArr2=[];
$json_obj1 = file_get_contents('json_1.json');
$jsonArr1 = json_decode($json_obj1, true);
$json_obj2 = file_get_contents('json_2.json');
$jsonArr2 = json_decode($json_obj2, true);
$finalArr=$jsonArr1;
$finalArr=array_merge_recursive($finalArr, $jsonArr2);
print_r($finalArr);
// file_put_contents('final_file.json', json_encode($finalArr)); // enable it if want to write output in json file
?>