Essetee's Website

Working with Json files under php

With your editor of choice paste the following content:

<?php

function create($data) {
    $currentData = json_decode(file_get_contents('data.json'), true);
    if (!is_array($currentData)) {
        $currentData = [];
    }
    $currentData[] = $data;
    file_put_contents('data.json', json_encode($currentData, JSON_PRETTY_PRINT));
}

function read($file) {
    if (!file_exists($file)) {
        return [];
    }
    $data = json_decode(file_get_contents($file), true);
    return is_array($data) ? $data : [];
}

function update($id, $updatedData) {
    $currentData = json_decode(file_get_contents('data.json'), true);
    foreach ($currentData as &$item) {
        if ($item['id'] == $id) {
            $item = array_merge($item, $updatedData);
            break;
        }
    }
    file_put_contents('data.json', json_encode($currentData, JSON_PRETTY_PRINT));
}

function delete($id) {
    $currentData = json_decode(file_get_contents('data.json'), true);
    foreach ($currentData as $index => $item) {
        if ($item['id'] == $id) {
            unset($currentData[$index]);
            break;
        }
    }
    file_put_contents('data.json', json_encode(array_values($currentData), JSON_PRETTY_PRINT));
}

function generateRandomString($length = 22) {
    $randomBytes = random_bytes($length); // Generate secure random bytes
    $base64UrlEncoded = rtrim(strtr(base64_encode($randomBytes), '+/', '-_'), '='); // Convert to base64 URL-safe format
    return substr($base64UrlEncoded, 0, $length); // Ensure the string is exactly 22 characters long
}
?>

Usage

Create operation

$id = generateRandomString($length = 22) // Create a random string with 22 chars for id
create(['id' => $id, 'name' => 'John Doe', 'email' => 'john@example.com']);

Read operation

$users = read(); // Reading or json file
print_r($users); // print the content

Update operation

$id = id_of_your_record
update($id, ['name' => 'Jane Doe']);

Delete operation

$id = id_of_your_record
delete($id);