<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2022/8/10
 * Time: 17:23
 */

namespace file;


class CsvHelper
{

    /**
     * 解析csv
     * @param $filepath [文件完整路径]
     * @return array [返回二维数组,解析结果]
     */
    public static function parse_csv($filepath)
    {
        $handle = fopen($filepath, 'r');//只读方式打开，将文件指针指向文件头]
        $out = array();
        $n = 0;
        while ($data = fgetcsv($handle, 10000)) {
            $num = count($data);
            for ($i = 0; $i < $num; $i++) {
                $row = mb_convert_encoding($data[$i], "UTF-8", "GBK");
                $out[$n][$i] = $row;
            }
            $n++;
        }
        fclose($handle); //关闭指针
        return $out;
    }

    /**
     * 导出csv
     * @param $titles [标题-数组]
     * @param $data [内容-二维数组]
     * @param string $filename [文件名]
     */
    public static function export_csv($titles, $data, $filename = "")
    {
        if (empty($filename)) {
            $filename = date('Ymd') . '.csv';
        }
        $str = "";
        if ($titles && is_array($titles)) {
            foreach ($titles as $title) {
                $str .= (empty($str) ? "" : ",") . $title;
            }
            $str = iconv('utf-8', 'gb2312', $str . PHP_EOL);
        }

        if ($data && is_array($data)) {
            foreach ($data as $line) {
                $line_str = "";
                foreach ($line as $row) {
                    $row_ = mb_convert_encoding($row, "GBK", "UTF-8");
                    $line_str .= (empty($line_str) ? "" : ",") . $row_;
                }
                $str .= $line_str . PHP_EOL;
            }
        }
        header("Content-type:text/csv");
        header("Content-Disposition:attachment;filename=" . $filename);
        header('Cache-Control:must-revalidate,post-check=0,pre-check=0');
        header('Expires:0');
        header('Pragma:public');
        exit($str);
    }

}