使用PHP读取文件并将其转换为文本文件

时间:2021-02-17 19:14:32

标签: php json

我有一个从外部网站读取的 json 文件,然后我想把它转换成一个 txt 文件,其中每条记录都在一个新行上,字段用“|”分隔

我被困在将其写入文件中。

 // Get the file from services 
$file = file_get_contents('https://services.swpc.noaa.gov/products/noaa-planetary-k-index.json');
// from https://stackoverflow.com/questions/3684463/php-foreach-with-nested-array so I can see the array structure
//  Output array
displayArrayRecursively($json);
function displayArrayRecursively($arr, $indent='') {
if ($arr) {
    foreach ($arr as $value) {
        if (is_array($value)) {
            //
            displayArrayRecursively($value, $indent . '|');
        } else {
            //  Output
            echo "$indent $value \n";
        }
    }
}

}

这将返回 Json 文件结构(我将其放入那里以查看是否读取了内容)以及值以“|”分隔的 JSON 文件。

我必须转换这个(缩短)。(在这里查看完整文件:https://services.swpc.noaa.gov/products/noaa-planetary-k-index.json

[["time_tag","Kp","Kp_fraction","a_running","station_count"],["2021-02-10 00:00:00.000","1","0.67","3 ","8"],["2021-02-10 03:00:00.000","0","0.33","2","8"],["2021-02-10 06:00:00.000 ","1","0.67","3","8"]]

显示为:

|时间标签 | Kp | Kp_fraction | a_running | station_count | 2021-02-10 00:00:00.000 | 1 | 0.67 | 3 | 8 | 2021-02-10 03:00:00.000 | 0 | 0.33 | 2 | 8 | 2021-02-10 06:00:00.000 | ....

我想要的是,写入txt文件: 2021-02-10 00:00:00.000|1|0.67|3|8 2021-02-10 03:00:00.000|0|0.33|2|8 等所有记录

那我该怎么做...

谢谢

1 个答案:

答案 0 :(得分:1)

我不知道这是否有助于解决您的问题,但我采用了不同的方法根据您的部分代码构建文本文件。

这是我的方法(基于您代码的第一部分和 documentation examples)的样子(行尾可能需要根据您的操作系统而有所不同——为此例如,我使用 \r\n 部分基于 an example from the documentation,部分基于过去的经验):

<?php
// Get the file from services
$file = file_get_contents('https://services.swpc.noaa.gov/products/noaa-planetary-k-index.json');
$json = json_decode($file);

// The process for writing output to a file
$fp = fopen('output.txt', 'w');
$i = 0;
foreach ($json as $lineData) {
    // Skip the header line according to your requirements.
    // If you need to include the header line, simply remove the $i related
    // code lines from this example.
    if ($i > 0) {
        // implode() lets you combine array pieces into a string
        fwrite($fp, implode('|', $lineData) . "\r\n");
    }
    ++$i;
}
fclose($fp);
?>

此外,如果您将来需要将其作为 csv 输出文件,您或许可以尝试这种方法(但请注意,日期时间戳在它们周围有双引号):

<?php
// Get the file from services
$file = file_get_contents('https://services.swpc.noaa.gov/products/noaa-planetary-k-index.json');
$json = json_decode($file);

// The process for writing output to a file
$fp = fopen('output.csv', 'w');
$i = 0;
foreach ($json as $lineData) {
    // Skip the header line according to your requirements.
    // If you need to include the header line, simply remove the $i related
    // code lines from this example.
    if ($i > 0) {
        fputcsv($fp, $lineData, $delimiter='|');
    }
    ++$i;
}
fclose($fp);
?>