Created
February 26, 2020 05:39
-
-
Save mubbashar/13850d7ca2cefd952c26698da961dcb5 to your computer and use it in GitHub Desktop.
PHP Code to write JSON file
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?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