简体   繁体   中英

How can I use json_encode in a while loop?

I've a litle probleme with my loop. I've to do a while loop because i encode really big files. But if I encode row per row I create every time a new JSON Object.

So Now I've this output.

[
    [
        "some logs and soo with informations ",
        "00:59:59",
        "the pure logssdf"
    ]
][
    [
        "some logs and soo with informations ",
        "00:59:52",
        "the pure logssdf"
    ]
]

But I need something like this:

[
            {
               "some logs and soo with informations ",
               "00:59:52",
               "the pure logssdf"
            },{
               "some logs and soo with informations ",
               "00:59:52",
               "the pure logssdf"
            }
]

And with this code I create this JSON-File:

$jsonFile = fopen('JSONLogs/' . $generatedName, "w");

$handle = @fopen($PATHTOLOG, "r");
if ($handle) {
    while (($buffer = fgets($handle, 4096)) !== false) {
        $pattern = '/^\w+\s+\d+\s('. preg_quote($SelectedTime) .':\d+.\d+).\d+.\d+\s(.+)/im';
        if (preg_match_all($pattern, $buffer, $matches, PREG_SET_ORDER)) {
            fwrite($jsonFile, json_encode($matches, JSON_PRETTY_PRINT));
        }
        else {

        }
    }

//var_dump($decodeData);
}
fclose($handle);
fclose($jsonFile);

So I decided to make my own "encoder", and just writing it in the File. Heres the final code wich worked for me.

$jsonFile = fopen('JSONLogs/' . $generatedName, "w");
$i=0;

$handle = @fopen($PathToTMP, "r");
if ($handle) {
    fwrite($jsonFile, "[");
    while (($buffer = fgets($handle, 4096)) !== false) {
        $pattern = '/^\w+\s+\d+\s('. preg_quote($SelectedTime) .':\d+.\d+).\d+.\d+\s(.+)/im';
        if (preg_match_all($pattern, $buffer, $matches, PREG_SET_ORDER)) {

            if ($i == 0) // Run this if block once.
            {
                fwrite($jsonFile, '{"0" : "'. $matches[0][0] .'" , '. "\n" . '  "1" : "'. $matches[0][1] .'", '. "\n" . ' "2" : "'. $matches[0][2] .'"}'. "\n" . '');
            }
            else
            {
                fwrite($jsonFile, ',{"0" : "'. $matches[0][0] .'" , '. "\n" . '  "1" : "'. $matches[0][1] .'", '. "\n" . ' "2" : "'. $matches[0][2] .'"}'. "\n" . ''); 
            }
            $i++;

        }
    }
    fwrite($jsonFile, "]");


//var_dump($decodeData);
}
fclose($handle);
fclose($jsonFile);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM