gpt4 book ai didi

php - 解析大型 JSON 文件

转载 作者:IT老高 更新时间:2023-10-29 00:01:04 25 4
gpt4 key购买 nike

我正在开发一个 cron 脚本,它可以访问 API,接收 JSON 文件(大量对象)并将其存储在本地。完成后,另一个脚本需要解析下载的 JSON 文件并将每个对象插入 MySQL 数据库。

我目前正在使用 file_get_contents()json_decode()。这将尝试在尝试处理之前将整个文件读入内存。这很好,除了我的 JSON 文件通常在 250MB-1GB+ 之间。我知道我可以增加我的 PHP 内存限制,但这似乎不是我心目中最好的答案。我知道我可以运行 fopen()fgets() 逐行读取文件,但我需要按每个 json 对象读取文件.

有没有一种方法可以读取每个对象的文件,或者是否有其他类似的方法?

最佳答案

试试这个库 https://github.com/shevron/ext-jsonreader

The existing ext/json which is shipped with PHP is very convenient and simple to use - but it is inefficient when working with large ammounts of JSON data, as it requires reading the entire JSON data into memory (e.g. using file_get_contents()) and then converting it into a PHP variable at once - for large data sets, this takes up a lot of memory.

JSONReader is designed for memory efficiency - it works on streams and can read JSON data from any PHP stream without loading the entire data into memory. It also allows the developer to extract specific values from a JSON stream without decoding and loading all data into memory.

关于php - 解析大型 JSON 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15373529/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com