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



我有一个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"]]>

示为:

| time_tag | Kp | Kp_fraction | a_running | station_count | 21-02-10 00:00:00.000 | 1 | 0.67 | 3 | 8 | 21-02-10 03:00:00.000 | 0 | 0.33 | 2 | 8 | 21-02-10 06:00:00.000 | .....

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

我该怎么做呢?

感谢

我不知道这是否会帮助你的问题,但我采取了一种不同的方法来构建基于你的部分代码的文本文件。

下面是我的方法(基于代码的第一部分和文档示例)看起来像(行结尾可能需要根据您的操作系统而不同—对于本例,我使用rn部分基于文档中的示例,部分基于过去的经验):

<?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) . "rn");
}
++$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);
?>

最新更新