function parseCsv($file) {
    // $file = __DIR__ . '/对账明细文件.txt';
    $fh = fopen($file, "r");
    if ($fh === false) {
        throw new \Exception('没有读取权限'.$file);
    }
    $row = 0;
    $labelList = [];
    $data = [];
    while (($item = fgetcsv($fh, 0, '|', )) !== FALSE) {
        $valueLength = count($item);
        if ($valueLength === 0 || ($valueLength === 1 && $item[0] === '') )  {
            continue; // 无效数据
        }

        if ($row === 0) { // 标题行
            $labelList = $item;
        }else{ // 数据行
            $tmp = [];
            for ($valueIndex = 0; $valueIndex < $valueLength; $valueIndex++) {
                $label = $labelList[$valueIndex];
                $value = $item[$valueIndex];
                $value = iconv('GBK', 'UTF-8//TRANSLIT//IGNORE', $value);
                $tmp[$label] = $value;
            }
            $data[] = $tmp;
        }
        $row++;
    }
    fclose($fh);
    return $data;
}

标签: none

添加新评论