将多个JSON对象读取或写入单个文件

时间:2018-07-18 13:21:39

标签: php json

我已经构建了一个脚本来抓取一些记录并将它们存储为json对象,以供以后使用。这是抓取过程的最后一步(Area-> Location-> ReportMeta-> ReportDetails ),使用此存储数据方法都可以正常工作。

问题是其中有很多,大约几十万。我尝试将它们全部累积到一个数组中,然后对其进行编码并将其写入文件,但是在接近完成之前,它已使内存最大化。我可以增加内存,但是我正在寻找一种更稳定/可复制/“开箱即用”的方法。如果可以的话,最好的做法。

我的第一个想法是,在抓取每个文件时将它们写到文件中。那是可行的,但我只剩下一个文件,其中包含许多单独的json对象,除非我进行一些特殊的格式化以将其恢复,否则几乎无法读取。

我正在寻找一种更好的方法或一些建议。

$reports_obj = new Report();
foreach($reports_array as $report){
    $report_details = $reports_obj->getReport($report['report_id'], $report['report_type']);
    $fp = fopen('report_details.json', 'a');
    fwrite($fp, json_encode($report_details));
    fclose($fp);
}

这给了我一大堆:

{
  "report_id": "12345",
  "report_type": "Type A",
  "facility_name": "Name here",
  "facility_type": "building",
  "report_date": "26-February-2018"
}
{
  "report_id": "12345",
  "report_type": "Type A",
  "facility_name": "Name here",
  "facility_type": "building",
  "report_date": "26-February-2018"
}
{
  "report_id": "12345",
  "report_type": "Type A",
  "facility_name": "Name here",
  "facility_type": "building",
  "report_date": "26-February-2018"
}

最好在具有正确的json结构的事实之后尝试查找/替换大文件,还是有更好的存储方式?我无法打开文件,例如,重新读取数据然后进行数组推送,因为这最终将具有与将它们全部累积到数组中一样的局限性。

至于“为什么” json?这只是一个软性偏爱。如果可能的话,我想留下来。

2 个答案:

答案 0 :(得分:0)

也许,您可以尝试以下方法:

$reports_obj = new Report();
foreach($reports_array as $report){
  $report_details[] = $reports_obj->getReport($report['report_id'],$report['report_type']);
}
$jsonjson=json_encode($report_details);
$report="{\"report\":".$jsonjson."}";
$fp = fopen('report_details.json', 'a');
fwrite($fp,$report);
fclose($fp);

如果有样品,也许我可以检查?

答案 1 :(得分:0)

您应该寻找NoSQL数据库。

如果您出于某种原因不希望/不想这样做,最好循环遍历所有报告,生成JSON并在之后写,而不是每次都打开和关闭文件

$result="";
   foreach($reports_array as $report){
    $report_details = $reports_obj->getReport($report['report_id'], $report['report_type']);
   $result .= json_encode($report_details)."\n\r";
}
$fp = fopen('report_details.json', 'a');
fwrite($fp,$result);
fclose($fp)
相关问题