[英]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.
我要做一个while循环因为我编码非常大的文件。 But if I encode row per row I create every time a new JSON Object.
但是如果我每行编码一行,我每次都会创建一个新的JSON对象。
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: 使用此代码,我创建了这个JSON文件:
$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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.