r/PHPhelp • u/rospondek • Jan 22 '26
Uploading huge JSON file into mySQL database through PHP
/r/SQL/comments/1qk1f7a/uploading_huge_json_file_into_mysql_database/
2
Upvotes
r/PHPhelp • u/rospondek • Jan 22 '26
1
u/HolyGonzo Jan 22 '26
The memory limit needs to be a little over twice the size of the length of the JSON.
Let's say the JSON is 900 megabytes. So it takes 900 megabytes of memory to hold that string in memory.
Then when you json_decode it, all of that data is being put into a big structure (either an object or an array, depending on how you called json_decode). So for at least a brief moment, you have a 900 megabyte string in memory AND a structure holding about 900 megabytes of data AND all the overhead of that structure (little pointers and such). So at minimum your limit would need to be about 1.8 gigs of memory, plus a little extra (depends on the complexity of the structure).
As soon as the string is decoded, you can clear the string (set it to null), which will allow garbage collection to recover that memory.
If the JSON structure and data is extremely simple and predictable, and you're limited on RAM, you COULD potentially use or even write a simple parser to extract the values incrementally but I would be very cautious about doing that. However, if you're working with a 900MB file, hopefully you have enough RAM to just set the memory limit high enough during the import.
If you can use a high enough memory limit, just dump the values to a CSV and then use mysql's LOAD DATA query to read the file.
1
u/colshrapnel Jan 22 '26
But what's memory available on your system?
3
u/obstreperous_troll Jan 22 '26
There are streaming JSON parsers for PHP like halaxa/json-machine that you could use. You'll probably have better luck with shoving CSV straight into mysql though: you could write your own json->csv converter with said streaming parser, but I suspect duckdb can probably do it in milliseconds on the command line.
1
u/insight_designs Jan 27 '26 edited Jan 27 '26
The problem is that json_decode(file_get_contents(...)) loads the entire 430MB file into memory (and decoded PHP arrays use even more memory than the raw JSON). You need to stream-parse the file instead.
Use a streaming JSON parser like https://github.com/halaxa/json-machine. It reads the file piece by piece so memory usage stays flat regardless of file size. A basic PDO example: