生成器yield真是個好東西,可以每次只讀取文件中一行的內(nèi)容,不占用寶貴的內(nèi)存資源
function getRows($file)
{
? ? if(!file_exists($file))
? ? {
? ? ? ? die("文件不存在");
? ? }
? ? $handle = fopen($file, 'rb');
? ? if($handle === false)
? ? {
? ? ? ? throw? new Exception('open file error');
? ? }
? ? while(feof($handle) === false)
? ? {
? ? ? ? yield fgetcsv($handle);
? ? }
? ? fclose($handle);
}
//轉(zhuǎn)換編碼格式,預(yù)防中文亂碼
function convert_arr($arr)
{
? ? return array_map(function($v){
? ? ? ? return mb_convert_encoding($v,'utf-8','gb2312');
? ? }, $arr);
}
foreach(getRows("abc.csv") as $k=>$row)
{
? ? if(is_array($row))
? ? {
? ? ? ? $row = convert_arr($row);
? ? ? ? file_put_contents("a.txt", json_encode($row,JSON_UNESCAPED_UNICODE)."\r\n", FILE_APPEND);
? ? }
}