/**如果对yield生成器不熟悉的话,请阅读《modernphp》第2章*如果是excel文件,请现将其转换为csv文件*注意文件的编码**///生成器functiongetRows($file){if(!file_exists($file)){d...
/*
* 如果对yield生成器不熟悉的话,请阅读《modern php》 第2章
* 如果是excel文件,请现将其转换为csv文件
* 注意文件的编码
*
*/
//生成器
function getRows($file)
{
if (!file_exists($file)) {
die("文件不存在");
}
$handle = fopen($file, 'r');
if ($handle === false) {
throw new Exception('open file error');
}
while (feof($handle) === false) {
//读取一行数据
yield fgetcsv($handle);
}
fclose($handle);
}
//转换编码格式,预防中文乱码
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);
}
}
全文详见:http://xpxw.com/?id=103