简体   繁体   中英

Return file content in json encoding

I have a txt file with this structure:

17/02/2016 [info] "hello"
17/02/2016 [debug] "world"

now I'm trying to read it with:

$fh = fopen("myfile.txt", "r");

while ($line = fgets($fh))
{
     echo json_encode($line);
}
fclose($fh);

the file is readed correctly but, in my chrome extension for try Rest API I get in the json tab:

unexpected string

the raw structure is this:

"17/02/2016 [info] "hello" \rn""17/02/2016 [debug] "world" \rn...

how I can return each line in json content? I want to this for have a better organization in a response.

Hi you can parse the input if you have the same string structure in your file and you create an array or object with your fields (date, info, text) and encode the array or object using json you can check for example preg_match for each line and use a regex to get the line structure into an array or object and at the end you can send your array of object or array of array as encoded json. you can use a regex like this ([0-9]*\\/[0-9]*\\/[0-9]*)\\s+\\[([^\\]]*)\\]\\s*\\"([^\\"]*)" and get your information from each line

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