简体   繁体   中英

How can i convert a text file to JSON using PHP?

I have data in a text file like this:

data1
data1
data1
data1
data1
data1
data1
data1
data2
data2
data2
data2
data2
data2
data2
data2
data3
data3
data3
data3
data3
data3
data3
data3

The file can contain any numbers of lines, but the data is always in 8 line sections. My desired output is valid JSON like this:

{
"data": [
    [
        "data1",
        "data1",
        "data1",
        "data1",
        "data1",
        "data1",
        "data1",
        "data1"
    ],
    [
        "data2",
        "data2",
        "data2",
        "data2",
        "data2",
        "data2",
        "data2",
        "data2"
    ],
    [
        "data3",
        "data3",
        "data3",
        "data3",
        "data3",
        "data3",
        "data3",
        "data3"
    ]
]

}

I have tried designing a php script to do this but i am hopeless with PHP, and i am nearly their, but can't get the formatting correct.

$tdcount = 1; $numtd = 8; // number of cells per row
$str = "{
    \"data\": [

     ";
$f = fopen("data.txt", "r");
if ( $f === FALSE ) {
    exit;
}

 while (!feof($f)) {
     $arrM = explode(",",fgets($f));
     $row = current ( $arrM );
     if ($tdcount == 1)
         $str .= "["; $str .= "\"$row\"";
     if ($tdcount == $numtd) {
         $str .= "]";
         $tdcount = 1;
     } else {
         $tdcount++;
     }
 }

 $str .= "] ] }";
 echo $str;
 exit;
?>

So i am wondering if theirs an easier way to do this and any example solutions that do what i require would be great.

2 main things - the first is don't try and build your own JSON, this quickly leads to issues. Secondly is try and use some of the built in functions to make the coding easier (comments in code)...

$numtd = 8;

// read the file into an array
$data = file("data.txt", FILE_IGNORE_NEW_LINES );

// use trim to remove any spaces
$data = array_map("trim", $data);

// array_chunk to split it into parts, output with json_encode
echo json_encode( ["data" => array_chunk($data, $numtd)], JSON_PRETTY_PRINT );

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