简体   繁体   English

如何使用 PHP 将文本文件转换为 JSON?

[英]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.该文件可以包含任意数量的行,但数据始终位于 8 行部分。 My desired output is valid JSON like this:我想要的输出是这样的有效 JSON:

{
"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.我曾尝试设计一个 php 脚本来执行此操作,但我对 PHP 无望,而且我几乎是他们的,但无法正确设置格式。

$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. 2 件主要事情 - 首先是不要尝试构建自己的 JSON,这会很快导致问题。 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 );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM