RT Cunningham

Manipulating JSON Text Files with PHP Functions and Routines

JSON text files

There are more functions and routines available for manipulating strings and text files in PHP than I care to mention. JavaScript Object Notation, or JSON, can be explored in JSON text files.

I’m using JSON for the project I’m working on. It may not be the easiest way to manipulate text files, but I like the simplicity of it.

JSON Text Files and Layouts

When I started working on the project, I chose JSON over other functions because it seemed like the easiest way to visually inspect the data. JSON text files can be edited directly with a standard text editor. The file names normally end with the “.json” file extension so other developers can know what’s being used.

I wanted files with multiple records, like a database, one record per line. With the PHP file function, I can read each line into an array and the new line character gets discarded. When I write, I can just add it back in to reassemble the file, line by line. Like a database, one of the fields is used as an ID. Each line is sorted by ID and then each record is sorted by its keys using the PHP ksort function.

Before I could start working with JSON text files, I needed to set up some functions before I could set up some routines.

JSON Functions and Routines

I won’t explain the functions in detail. You can visit the JSON manual area at php.net to see what I’m doing.

function json_d($array) {
$array = json_decode($array, true);
return $array;
}
function json_e($array) {
$array = json_encode($array, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_NUMERIC_CHECK);
return $array;
}

I use a single PHP function to read in the entire file:

$record = file('/path-to/filename');

Then I use a routine to manipulate each line, like this:

foreach ($record as $field) {
$field = json_d($field);
$id = $field['id'];
// do something
$field = json_e($field) . "\n";
}

This routine is obviously the simplest approach to changing a variable. I have some routines that are way more complex. I use the PHP continue function to skip lines, and other flow-control functions. The nice thing about using JSON text files instead of databases (or database tables), is that the data uses a tiny amount of memory compared to starting a full-blown database server, with no data at all.

With my project, I load most of the data from the JSON text files when I initialize the script. I once calculated how much memory I could potentially use all at once, with thousands of records. It was ridiculously low.

All of this is just part of what I’m doing with my homegrown CMS. Even if I never finish this project, I will have learned how to manipulate JSON text files for other projects. Actually, I already finished it – I’m in the process of rewriting a lot of it. I can’t share it as is.

Share:    

RT Cunningham
February 5, 2019
Web Development