php write to json file – How to generate Json File in PHP ?

php write to json file Use file_put_contents() Function to Generate a .Json File in PHP. JSON (JavaScript Object Notation) is a lightweight data-interchange format.

php write to json file

i am going to generate a JSON file in PHP by using an array. Creating a JSON object with PHP is simple: You just need to use the json_encode() function.

How to Write JSON to File in PHP?

Write JSON to File in PHP

// array
$array = Array (
    "0" => Array (
        "id" => "GG55241",
        "name" => "Pinkal Dave",
        "nominate" => "devloper Architect"
    "1" => Array (
        "id" => "AK5421",
        "name" => "Jaya Badhuri",
        "nominate" => "Senior Programmer"
    "2" => Array (
        "id" => "FF4523",
        "name" => "Disha Kaliya",
        "nominate" => "Office Manager"

// encode array to json
$json = json_encode(array('data' => $array));

//write json to file
if (file_put_contents("data.json", $json))
    echo "JSON file created successfully...";
    echo "Oops! Error creating json file...";

// data.json

// {"data":[{"id":"GG55241","name":"Pinkal Dave","nominate":"devloper Architect"},{"id":"AK5421","name":"Jaya Badhuri","nominate":"Senior Programmer"},{"id":"FF4523","name":"Disha Kaliya","nominate":"Office Manager"}]}

append data to json file php

file_put_contents php json file

$data[] = $_POST['data'];

$inp = file_get_contents('results.json');
$tmembers_Array = json_decode($inp);
array_push($tmembers_Array, $data);
$jsonData = json_encode($tmembers_Array);
file_put_contents('results.json', $jsonData);

How to generate .json file with PHP?

$sql="select * from Articles limit 20"; 

$response = array();
$articles = array();
while($row=mysql_fetch_array($data)) { 

  $articles[] = array('title'=> $title, 'url'=> $url);

$response['articles'] = $articles;

$fp = fopen('results.json', 'w');
fwrite($fp, json_encode($response));


Don’t Miss : How To Insert Json Data Into Mysql Using Php

I hope you get an idea about php write to json file.
I would like to have feedback on my
Your valuable feedback, question, or comments about this article are always welcome.
If you enjoyed and liked this post, don’t forget to share.