【问题标题】:Streaming JSON parser with fopen(), fgets() and PHP使用 fopen()、fgets() 和 PHP 流式传输 JSON 解析器
【发布时间】:2014-09-18 07:55:32
【问题描述】:

JSON 文件的 sn-p。

{ 
"products": { 
"product" : [
{ "name" : "Desktop", "price" : 799.99, "memory" : "4GB"},
{ "name" : "Laptop", "price" : 999.99, "memory" : "3GB"},
{ "name" : "Notebook", "price" : 899.99, "memory" : "2GB"}
] }}

我需要解析一个非常大的 JSON 文件,然后根据用户查询显示相关的搜索结果。我想避免使用 json_decode 或 file_get_contents 将整个文件加载到内存中,而是逐行解析文件。

$search_results = "";
$Json_file = fopen("products.json", "r");
while (!feof($Json_file)) {
$line_of_data .= fgets($Json_file);
$decoded_line = json_decode($line_of_data);

此时我想使用 if 语句,以便 fgets() 函数仅从 JSON 文件中提取“价格”值低于 900 的数据。下面的 if 语句不起作用 - 它会导致页面完全空白,但代码在没有 if 语句的情况下工作正常。我的问题是:是否有一种“性能友好”的方式来编写 if 语句(在代码中的这一点),以便可以过滤掉不相关的 JSON 数据而不放在下面的 search_results 变量中?或者有没有更好的方法以“性能友好”的方式逐行解析大型 JSON 文件?

if ($decoded_line->products->product->price < 900) {  //assuming a site visitor is searching for an item under $900
$search_results .= decoded_line->products->product;
}
}

通过在上面的 if 语句中过滤掉不相关的 JSON 数据,我认为当我们在这里使用 json_decode 时它会有助于整体性能。

$data = json_decode($search_results);
$product = $data->products->product;

foreach($product as $Product) {
echo $Product->name . " " . $Product->price;
echo "<br>";
}

fclose($Json_file);

非常感谢您的任何建议!

【问题讨论】:

    标签: php json parsing fopen fgets


    【解决方案1】:

    是否可以选择将 JSON 写入本地数据库(如果还没有的话)并使用 ajax 调用和 onkeychange 事件以过滤方式返回搜索结果?

    【讨论】:

    • 我想避免使用 ajax 和其他任何面向客户端的东西。我的主要目标是尽早过滤掉不相关的数据(来自 JSON 文件),以便 JSON_decode 解码的内容更少(稍后在代码中)
    • 您仍然可以通过数据库过滤它吗?
    • 有没有办法在没有数据库的情况下进行过滤(我尝试使用 if 语句过滤的代码中的 IE)?
    • 有使用数组操作。将 JSON 解析为一个数组,然后您可以进行比较、排序等,但我看到的唯一方法是使用数据库,您可以在没有整个数据集在内存中的情况下对其进行处理。当然,除非您只需要一个小子集,并且不必不断地查询整个 JSON 文件。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-07-05
    • 2019-01-10
    • 2019-06-30
    • 1970-01-01
    • 2014-03-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多