undefinedfix
Sign in

PHP file download

NWRColoradoSprings edited in Sun, 12 Jun 2022

There is a set of data, to write it to TXT, and then download the txt file

How to realize this

3 Replies
lethr
commented on Sun, 12 Jun 2022

PHP reads the data of the CSV file and outputs it. It converts the CSV file to the corresponding TXT file and outputs it

$file = fopen("log.txt", "r");
        $user=array();
        $i=0;
//输出文本中所有的行,直到文件结束为止。
        while(! feof($file))
        {
            $user[$i]= fgets($file);//fgets()函数从文件指针中读取一行
            $i++;
        }
        fclose($file);
        $user=array_filter($user);
        print_r($user);

download



class UserExcelController extends Controller
{
    /**
     * 导出报表功能
     * @param $dataArr 数据源 (二维结构);
     * @param $fieldArr 字段信息(一维数组,键值存放$dataArr中存在的key名,对应的value存放要导出表头的字段名称) ;
     * @param $tname excel表名(默认自动在最后加上导出的时间戳);
     * @author qingfeng.guo
     * 2016-06-21
     */
    function exportExcel($dataArr,$fieldArr,$tname="报表导出")
    {
        if(!is_array($fieldArr) || empty($fieldArr))
            die("导出异常,请重试!");

        if(!empty($dataArr) && count($dataArr) > 10000)
            die("单次导出的数据量过大(≥10000条),请分批导出!");

        $thead = ''; //表头
        $tbody = ''; //表数据
        $ttail = ''; //表尾
        $clos = count($fieldArr); //列数(字段量)
        //生成表头
        $thead .= '<tr>';
        foreach($fieldArr as $k => $v)
        {
            $thead .= '<td style="color:#fff;background-color:green;">'.$v.'</td>';
        }
        $thead .= '</tr>';
        //生成表尾
        $ttail = '<tr><td colspan="'.$clos.'"> 报表内容:'.$tname.' , 导出时间:'.date("Y-m-d H:i:s").' </td></tr>';

        //生成需要导出的数据源
        $datas = array();
        foreach($dataArr as $k => $v)
        {
            $v['created_at'] = date('Y-m-d H:i:s',$v['created_at']);
            $fieldFormat = $fieldArr; //这里需要复制原本的字段格式,以防标题和内容没对应上
            if(!empty($v) && is_array($v))
            {
                foreach($v as $k2 => $v2)
                {
        //根据key值决定当前字段是否需要导出
                    if(array_key_exists($k2, $fieldArr))
                    {
                        $fieldFormat[$k2] = $v2;
                    }
                }
            }
            $datas[] = $fieldFormat;
        }
        //生成表体
        foreach ($datas as $k => $v)
        {
            $tbody .= '<tr>';
            foreach($v as $k2 => $v2)
            {
                if(!is_numeric($v2))
                {
                    $tbody .= '<td style="vnd.ms-excel.numberformat:@">'.$v2.'</td>';
                }else{
                    $tbody .= '<td>'.$v2.'</td>';
                }
            }
            $tbody .= '</tr>';
        }

        $content = $thead.$tbody.$ttail;
        header("content-type:application/vnd.ms-excel; charset=utf8");
        header("Content-Disposition:attachment;filename={$tname}".time().".xls");
        echo "<table align='center' border=1 bgcolor='F8F7ED'>";
        if(mb_detect_encoding($content) != 'UTF-8')
        {
            echo iconv('UTF-8',"GB2312",$content);
        }else{
            echo $content;
        }
        echo "</table>";
    }



    //查出所需要导出数据
    public function userExcel(Request $request){
        $list = User::join('users as u','u.id','=','users.pid')
            ->select('users.id','users.nickname','u.nickname as u_nickname','users.phone','u.phone as u_phone','users.email','users.created_at')
            ->paginate(10)->toArray();
        $list =$list['data'];
        $fieldArr = array(
            'id' => '用戶id',
            'nickname' => '用户名',
            'u_nickname' => '推荐人',
            'phone' =>'手机号',
            'u_phone'=>'推荐人手机号',
            'email'=>'邮箱',
            'created_at'=>'加入时间',
        );
        $this->exportExcel($list, $fieldArr,'用戶表');
    }
}
dinara_pulseway
commented on Mon, 13 Jun 2022

<?php

$myfile = fopen("newfile.txt", "w") or die("Unable to open file!");
$txt = "Bill Gates\n";
fwrite($myfile, $txt);
$txt = "Steve Jobs\n";
fwrite($myfile, $txt);
fclose($myfile);

? > this is an example on w3school http://www.w3school.com.cn/ph...


Paste a section of the code before downloading the CSV file, the principle is the same

        set_time_limit(0);
        ini_set('memory_limit', '1024M');
        $fileName = 'WinterStudentCount-'.date('YmdHis', time());
        header('Content-Type: application/vnd.ms-execl');
        header('Content-Disposition: attachment;filename="' . $fileName . '.csv"');
        header('Cache-Control: max-age=0');
        //打开php标准输出流
        //以写入追加的方式打开
        $fp = fopen('php://output', 'a');
        // 标题
        $info = ['序号','中学','年度','人数','录取人数','录取率'];
        foreach ($info as $k => $v) {
            $title[] = iconv('UTF-8', 'gbk//IGNORE', $v);
        }
        //获取学校表
        $data = WinterStudentDataForm::find()->where($map);
        $datainfo = $data->select(['school','year','number','enroll_number'])->asarray()->all();
        for ($i=0; $i < count($datainfo); $i++) { 
            $datainfo[$i]['rate'] = $datainfo[$i]['enroll_number'].' \ '.$datainfo[$i]['number'];
        }
        $year = isset($map['year'])?$map['year']:'0';
        $number_sum = $data->sum('number');
        $enroll_number_sum = $data->sum('enroll_number');
        $info_count = ['',iconv('UTF-8', 'gbk//IGNORE', '汇总'),$year,$number_sum,$enroll_number_sum,$enroll_number_sum.' \ '.$number_sum];
        if($datainfo) {
            //将标题写到标准输出中
            $i = 1;
            fputcsv($fp, $title);
            foreach($datainfo as $key=> $item) {
                //这里必须转码,不然会乱码
                $order = $i++;
                foreach($item as $k => $v){
                    $row['order'] = $order;
                    $row[$k] = iconv('UTF-8', 'gbk//IGNORE', $v);
                }
                fputcsv($fp, $row);
            }
            fputcsv($fp, $info_count);
        }

urytf
commented on Mon, 13 Jun 2022

You can think like this, first write the array to TXT, because the array can't be written directly, you can process the data before writing, such as JSON. The second part calls the download interface to download the file to the local

lock This question has been locked and the reply function has been disabled.