我有一个从外部网站读取的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 | 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|82021-02-10 03:00:00.000|0|0.33|2|8等等
那我该怎么做呢。
谢谢
发布于 2021-02-18 03:34:41
我不知道这是否有助于解决您的问题,但我在基于您的部分代码构建文本文件时采用了一种不同的方法。
下面是我的方法(基于代码的第一部分和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);
?>https://stackoverflow.com/questions/66248562
复制相似问题