Skip to content

Instantly share code, notes, and snippets.

@mubbashar
Created February 26, 2020 05:39
Show Gist options
  • Select an option

  • Save mubbashar/13850d7ca2cefd952c26698da961dcb5 to your computer and use it in GitHub Desktop.

Select an option

Save mubbashar/13850d7ca2cefd952c26698da961dcb5 to your computer and use it in GitHub Desktop.
PHP Code to write JSON file
<?php
public function writeJsonFile($jsonFileNamePath, $jsonData)
{
if (file_exists($jsonFileNamePath) ) {
preg_match('/^\[(.+)\]$/', $jsonData, $removeBracket);
$jsonFileHandle = fopen($jsonFileNamePath, 'c');
// move back a byte
fseek($jsonFileHandle, -1, SEEK_END);
$pointerPosition = ftell($jsonFileHandle);
if ($pointerPosition > 0) {
// add the new json string
fwrite($jsonFileHandle, ',' . $removeBracket[1] . ']');
} else {
fwrite($jsonFileHandle, $jsonData);
}
} else {
$jsonFileHandle = fopen($jsonFileNamePath, 'w');
// write the first string
fwrite($jsonFileHandle, $jsonData);
}
fclose($jsonFileHandle);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment