以json内容格式返回文件
I have a txt file with this structure:
17/02/2016 9:50 [info] "hello"
17/02/2016 10:20 [debug] "world"
now I'm trying to read it with:
$fh = fopen($this->_logPath, "r");
$content = array();
while ($line = fgets($fh))
{
array_push($content, $line);
}
fclose($fh);
return json_encode($content);
the file is readed correctly but, in my chrome extension for try Rest API I get in the json tab:
unexpected string
how I can return each line in json content? For example a result like this:
"trace": {
info: {
date: {
"17/02/2016 9:50" {
-"content": "hello"
}
}
}
debug: {
date: {
"17/02/2016 10:20" {
-"content": "world"
}
}
}
}
or if someone have a better organization I'll glad to see.
我有一个具有这种结构的txt文件: p>
17 / 02/2016 9:50 [info]“你好”
17 / 02/2016 10:20 [调试]“世界”
code> pre>
现在我正在尝试 阅读它: p>
$ fh = fopen($ this-> _logPath,“r”);
$ content = array();
而($ line = fgets($ fh))
{
array_push($ content,$ line);
}
nclclose($ fh);
return json_encode($ content);
code> pre>
文件被正确加入,但是在我的chrome扩展程序中尝试使用Rest API我进入json选项卡: p>
意外字符串 p>
blockquote>
如何返回json内容中的每一行? 例如,结果如下: p>
“trace”:{
info:{
date:{
“17/02/2016 9:50”{\ n - “content”:“hello”
}
}
}
debug:{
date:{
“17/02/2016 10:20”{
- “content”:“world “
}
}
}
}
code> pre>
或者如果有人有更好的组织,我很乐意看到。 p>
DIV>
I would choose a structure like this:
{
"trace":[
{
"date":"17/02/2016 9:50",
"level":"debug",
"message":"hello"
},
{
"date":"17/02/2016 9:50",
"level":"debug",
"message":"hello"
}
]
}
Notice that trace contains an array of logitems. To parse your file, following should work:
$fh = fopen($this->_logPath, "r");
$content = array();
$content["trace"] = array();
while ($line = fgets($fh))
{
$raw = preg_split("/[\[\]]/", $line); //splits string at [ and ], results in an array with three items
$entry = array();
$entry["date"] = trim($raw[0]);
$entry["level"] = trim($raw[1]);
$entry["message"] = trim($raw[2]);
$content["trace"][] = $entry;
}
fclose($fh);
return json_encode($content);
for experimenting with json you may enjoy https://jsonformatter.curiousconcept.com/ which I've always found very useful.