📲 Download Our Apps

EMI Calculator

Download EMI Calculator

SOA Games

Download SOA Games

SOA Technology App

Download SOA Technology

BMI Checker

Download BMI Checker

Task Jira

Download Task Jira

Laughing Adda

Download Laughing Adda

📅 हिंदी कैलेंडर ऐप डाउनलोड करें

Download Shubhcalendar App

create and append json file php

To create and append data to a JSON file using PHP, the following steps are required:

  • Define the JSON file path: Specify the name and location of the JSON file.

Code

    $filename = 'data.json';
  • Prepare the new data: Create an associative array in PHP representing the data to be appended.

Code

    $newData = [
        'name' => 'Aditya Singh',
        'age' => 43,
        'city' => 'India'
    ];
  • Read existing data (if any): Check if the JSON file exists. If it does, read its contents and decode them into a PHP array.

Code

    if (file_exists($filename)) {
$currentData = file_get_contents($filename);
$arrayData = json_decode($currentData, true); // true for associative array
} else {
$arrayData = []; // Initialize an empty array if file doesn't exist
}
  • Append new data: Add the $newData to the $arrayData. If the JSON file stores an array of objects, append the new data as a new element in that array.

Code

    $arrayData[] = $newData;
  • Encode and write to file: Convert the updated PHP array back into a JSON string using json_encode() and write it to the file using file_put_contents().

Code

    $jsonData = json_encode($arrayData, JSON_PRETTY_PRINT); // JSON_PRETTY_PRINT for readability
file_put_contents($filename, $jsonData);

This process ensures that new data is added without overwriting existing content, while also handling the creation of the file if it doesn’t already exist.




Leave a Reply

AI Spiritual Tools & Interactive Experiences

Explore powerful AI-driven tools for daily guidance, spirituality, fun quizzes, and self-discovery.

Today’s Quote

Get inspiring daily quotes powered by AI to motivate and guide your day.

Explore Now

AI Tarot Card Reader

Reveal insights about your future, love, and career with AI tarot readings.

Read Tarot

Love Match Calculator

Check compatibility and love predictions using AI-based analysis.

Check Match

Fortune Cookie

Open an AI fortune cookie and receive wisdom, luck, and fun messages.

Open Cookie

Quiz Categories

Engage with knowledge-based and fun quizzes across multiple categories.

Start Quiz

Panchang Calendar

View daily Panchang, auspicious timings, tithi, nakshatra, and festivals.

View Panchang

Online Numerology

Discover your destiny number, life path, and numerology predictions.

Calculate Now

Spiritual Feeds

Stay connected with spiritual thoughts, mantras, and divine content.

View Feeds

Quiz Hub

Attempt trending quizzes on GK, spirituality, festivals, and more.

Explore Quizzes