PHP导出数据到CSV文件函数:


/**
* 导出数据到CSV文件
*
* @param array $data 二维数组(模拟数据表记录)
* @param array $titleList 标题数组列表
* @param string $fileName CSV文件名
*/
function csv_export(&$data, $titleList = array(), $fileName = '')
{
    ini_set("max_execution_time", "3600");
    $csvData = '';

    // 标题
    $nums = count($titleList);
    for ($i = 0; $i < $nums - 1; $i++)
    {
        $csvData .= '"' . $titleList[$i] . '",';
    }
    $csvData .= '"' . $titleList[$nums - 1] . ""rn";

    foreach ($data as $key => $row)
    {
        $i = 0;
        foreach ($row as $_key => $_val)
        {
            $_val = str_replace(""", """", $_val);
            if ($i < ($nums - 1))
            {
                $csvData .= '"' . $_val . '",';
            }
            elseif ($i == ($nums - 1))
            {
                $csvData .= '"' . $_val . ""rn";
            }
            $i++;
        }
        unset($data[$key]);
    }
    $csvData = mb_convert_encoding($csvData, "cp936", "UTF-8");
    $fileName = empty($fileName) ? date('Y-m-d-H-i-s', time()) : $fileName;
    $fileName = $fileName . '.csv';
    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');
    echo $csvData;
    exit();
}

使用示例:

$data = array(
    array(
        'name' => '张三',
        'score' => 80,
        'grade' => 'A'
    ),
    array(
        'name' => '李四',
        'score' => 70,
        'grade' => 'A'
    ),
    array(
        'name' => '王五',
        'score' => 80,
        'grade' => 'A'
    ),
    array(
        'name' => '赵六',
        'score' => 203,
        'grade' => 'B3'
    )
);

$titleList = array('姓名', '总分', '等级');
$fileName = '码农资源网(www.codesou.cn)学员成绩表';

csv_export($data, $titleList, $fileName);