【问题标题】:Working with large .JSON file (PHP)使用大型 .JSON 文件 (PHP)
【发布时间】:2014-01-30 06:43:01
【问题描述】:

我有一个大的 JSON 文件,我正试图将它插入数据库。当使用json_decode 将其转换为数组以将其插入数据库时​​,出现错误:

Fatal error:  Allowed memory size of 134217728 bytes exhausted (tried to allocate 188340087 bytes) in site.php on line 48

有没有更有效的方法来翻译这些数据,而不必逐行读取和缓冲。如果没有,我应该如何阅读每一行并对其进行解码?我会很感激任何帮助。

{"items":[ {
  "itemId" : 17730521,
  "parentItemId" : 17730521,
  "name" : "1000 lb Flat-Free Super Steel P-Handle Hand Truck",
  "msrp" : 110.0,
  "salePrice" : 87.94,
  "upc" : "053417031815",
  "categoryPath" : "Home Improvement/Tools/Lifting Equipment",
  "shortDescription" : "The Flat-Free 1000-pound Heavy-Duty Hand Truck is one tough truck with its heavy-duty oversized frame, extra large base plate and curved frame back that easily transports boxes or cylinders.",
  "longDescription" : "<br><b>1000 lb Flat-Free Super Steel P-Handle Hand Truck:</b><ul><li>Heavy-duty flat-free 10" solid rubber wheels</li><li>1000 lb capacity</li><li>Extra large 20" x 8" base plate for bulky and oversized loads</li><li>50" height for larger loads</li><li>P-loop handle for easy 1- or 2-hand control</li><li>Large fenders to protect load from damage</li><li>Dimensions: 50"L x 21"W x 19"H</li><li>1-year warranty</li></ul>",
  "brandName" : "Generic",
  "thumbnailImage" : "this is a link",
  "mediumImage" : "this is a link",
  "largeImage" : "this is a link",
  "productTrackingUrl" : "",
  "ninetySevenCentShipping" : false,
  "standardShipRate" : 0.0,
  "twoThreeDayShippingRate" : 79.97,
  "overnightShippingRate" : 73.97,
  "marketplace" : false,
  "shipToStore" : true,
  "freeShipToStore" : true,
  "modelNumber" : "H5986",
  "productUrl" : "",
  "categoryNode" : "1072864_1031899_1043985",
  "bundle" : false,
  "clearance" : true,
  "preOrder" : false,
  "stock" : "Available",
  "availableOnline" : true,
  "bestMarketplacePrice" : {
    "price" : 120.0,
    "sellerInfo" : "PlumStruck",
    "standardShipRate" : 5.99,
    "availableOnline" : true,
    "clearance" : false
  }
}, 
...
]}

【问题讨论】:

  • 还有更多可以分配的内存吗?
  • 我已经尝试分配内存,不幸的是在加载文件时它使用了太多我的服务器资源。我正在努力使其重量轻,效率高,不妨碍记忆。
  • 这个 JSON 数组是什么结构的?逐行阅读有什么问题。如果它只是一个数组并且更好但主要是行分隔,这真的很容易。
  • 它是上面的一个。我忘了包括结构。
  • 有什么办法可以预先分割你的文件吗?

标签: php arrays database json decode


【解决方案1】:

有一个很好的人写了这个库来解析大型 JSON https://github.com/kuma-giyomu/JSONParser

正如作者所说:

如何:

阅读 test/test.php 文件以获取真实示例。但基本上:

创建解析器实例

为您感兴趣的事件设置处理程序

运行 parseDocument 方法

等着看

【讨论】:

    猜你喜欢
    • 2011-05-02
    • 1970-01-01
    • 2018-08-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-21
    相关资源
    最近更新 更多