If you want to add another element of the array to the JSON file, as shown in the example, open the file and search to the end. If the file already has data, look back one byte to overwrite ] after the last write, then write , plus new data minus the initial [ new data. Otherwise, this is your first element of the array, so just write your array as usual.
Sorry, I donโt know enough about PHP to publish real code, but I did it in Obj-C, and this allowed me to avoid reading the entire file in the first place, just to add to the end:
NSArray *array = @[myDictionary]; NSData *data = [NSJSONSerialization dataWithJSONObject:array options:0 error:nil]; FILE *fp = fopen(fname, "r+"); if (NULL == fp) fp = fopen(fname, "w+"); if (fp) { fseek(fp, 0L, SEEK_END); if (ftell(fp) > 0) { fseek(fp, -1L, SEEK_END); fwrite(",", 1, 1, fp); fwrite([data bytes] + 1, [data length] - 1, 1, fp); } else fwrite([data bytes], [data length], 1, fp); fclose(fp); }
source share