Reputation: 322
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.
Upvotes: 0
Views: 531
Reputation: 2663
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.
Upvotes: 3