How to Write JSON to File in PHP

On 5/05/2016

Hi! In this post we'll see how to write json to file in php. JSON formatted data is more verbose and human readable. If you want to store data which is easily processable in the future, then json format would be a preferable choice nowadays. In the past I have written several tutorials about handling json data and some of the blog readers asked for a solution to save the json data in a file. I thought writing a separate tutorial on the topic will benefit everyone. Here I have given the php script to write json formatted string to file.

Write JSON to File in PHP

The below php script takes up an multi-dimensional associative array, encode it into json string and then write it into a file.

<?php
// array
$array = Array (
    "0" => Array (
        "id" => "MMZ301",
        "name" => "Michael Bruce",
        "designation" => "System Architect"
    ),
    "1" => Array (
        "id" => "MMZ385",
        "name" => "Jennifer Winters",
        "designation" => "Senior Programmer"
    ),
    "2" => Array (
        "id" => "MMZ593",
        "name" => "Donna Fox",
        "designation" => "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...";
else 
    echo "Oops! Error creating json file...";

// data.json

// {"data":[{"id":"MMZ301","name":"Michael Bruce","designation":"System Architect"},{"id":"MMZ385","name":"Jennifer Winters","designation":"Senior Programmer"},{"id":"MMZ593","name":"Donna Fox","designation":"Office Manager"}]}
?>
  • The function json_encode(array('data' => $array)) encodes array to json along with a name "data".
  • The function file_put_contents("data.json", $json) writes/stores $json string to the specified file "data.json".

Also Read:

Likewise you can easily write json to file in php. I hope you find this script useful. Let me know your thoughts through comments!

5 comments:

  1. Wow amazing i saw the article with execution models you had posted. It was such informative. Really its a wonderful article. Thank you for sharing and please keep update like this type of article because i want to learn more relevant to this topic.


    Hadoop Training in Chennai

    ReplyDelete
  2. awesome tutorial valli, keep posting .. :)
    btw how much you earn from affiliate marketing and using adsense in your blog ?

    thanks waiting for reply...

    ReplyDelete
  3. nice! thank you so much! Thank you for sharing. Your blog posts are more interesting and impressive. I think there are many people like and visit it regularly, including me.
    192.168.1.1

    ReplyDelete
  4. nice! thank you so much! Thank you for sharing. Your blog posts are more interesting and impressive. I think there are many people like and visit it regularly, including me.
    192.168.1.1

    ReplyDelete

Contact Form

Name

Email *

Message *