在开发一个数据导入导出功能时,遇到了一个挑战:需要处理的JSON文件非常大,动辄几百MB甚至更大。使用PHP内置的
json_decode
bcncommerce/json-stream
bcncommerce/json-stream
salsify/jsonstreamingparser
rayward/json-stream
bcncommerce/json-stream
使用Composer安装
bcncommerce/json-stream
<pre class="brush:php;toolbar:false;">composer require bcncommerce/json-stream
使用JSON Writer的示例:
假设我们需要导出一个产品目录到JSON文件,可以这样使用
JSON Writer
<pre class="brush:php;toolbar:false;">use Bcn\Component\Json\Writer;
$filename = 'catalog.json';
$fh = fopen($filename, "w");
$writer = new Writer($fh);
$writer->enter(Writer::TYPE_OBJECT); // 进入根对象
$writer->write("catalog", $catalog['id']); // 写入键值对
$writer->enter("items", Writer::TYPE_ARRAY); // 进入 items 数组
foreach($catalog['products'] as $product) {
$writer->write(null, [ // 写入数组项
'sku' => $product['sku'],
'name' => $product['name']
]);
}
$writer->leave(); // 离开 items 数组
$writer->leave(); // 离开根对象
fclose($fh);使用JSON Reader的示例:
Easily find JSON paths within JSON objects using our intuitive Json Path Finder
30
假设我们需要读取上面导出的产品目录JSON文件,可以这样使用
JSON Reader
<pre class="brush:php;toolbar:false;">use Bcn\Component\Json\Reader;
$filename = 'catalog.json';
$fh = fopen($filename, "r");
$reader = new Reader($fh);
$reader->enter(Reader::TYPE_OBJECT); // 进入根对象
$catalog['id'] = $reader->read("catalog"); // 读取 catalog 节点
$reader->enter("items", Reader::TYPE_ARRAY); // 进入 item 数组
while($product = $reader->read()) { // 读取 product 结构
$catalog['products'][] = $product;
}
$reader->leave(); // 离开 item 节点
$reader->leave(); // 离开根对象
fclose($fh);通过使用
bcncommerce/json-stream
bcncommerce/json-stream
以上就是JSON文件过大导致内存溢出?bcncommerce/json-stream帮你轻松处理海量数据的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号