<?php
$path = dirname(__FILE__);//获取当前文件夹位置
$result = array();
//读取所有文件路径函数
function traversing($path, &$result)
{
$curr = glob($path . '/*');
if ($curr) {
foreach ($curr as $f) {
if (is_dir($f)) {
traversing($f, $result);
} elseif (strtolower(substr($f, -4)) == '.txt') {//如果是后四位是.txt文件则写入array数组
array_push($result, $f);
}
}
}
}
//将读取内容写入csv文件
function put_csv_my(&$dataList)
{
$fp = fopen('321.csv', 'a');
foreach ($dataList as $key => $value) {
foreach ($value as &$value1) {
$value1 = "\t" . $value1 . "\t";
}
unset($value1);
fputcsv($fp, $value);
}
fclose($fp);
}
traversing($path, $result);//调用函数获取所有txt文件的路径
foreach ($result as $pathTxt) {//遍历获取的所有txt文件,读取文件以gbk格式存储
$file_name = $pathTxt;
$file = fopen($file_name, "r");
$data = [];
while (!feof($file)) {
$str = fgets($file);
$str = iconv("UTF-8", "GB2312//IGNORE", $str);
$data[] = explode("\t", $str);
}
fclose($file);
put_csv_my($data);//将读取的内容,调用函数写入csv文件
}