duandong9195 2018-10-22 15:40
浏览 169
已采纳

php - fputcsv不能使用stdClass类型的对象作为数组

I use post method to download csv using php with fputcsv when i using get method it works, but when using post it give me error, cannot use stdClass as array, people mention to use json_decode but i'm not sure wher to place it,

I use laravel

CODE :

public function csv (Request $request) {

    $storage_path = storage_path();

    $from = date($request->from_date);
    $to = date($request->to_date);

    $table = DB::table('registrations')->whereBetween('created_at', [$from, $to])->get();



    $filename = "data.csv";
    $handle = fopen('php://output', 'w+');

    fputcsv($handle, array('No', 'Nama', 'Nomor Telepon', 'Email', 'Tempat Tinggal',
        'Bank', 'Kartu Kredit', 'Rumah', 'Mobil', 'Luar Negeri', 'Penghasilan'));

    foreach($table as $row) {
            fputcsv($handle, array( $row['id'], $row['name'], $row['phonenumber'], $row['email'],
                            $row['umur'], $row['tempattinggal'],
                            $row['bank'], $row['kartukredit'], $row['rumah'],
                            $row['keluarnegeri'], $row['penghasilan'] ));
    }

    fclose($handle);

    $headers = array(
            'Content-Type' => 'text/csv',
    );

    return Response::download($filename, 'data.csv', $headers);
}

the error happen to be on foreach,when i remove the for each , i can donwload the csv, but in badly format

  • 写回答

3条回答 默认 最新

  • dongmaonao0505 2018-10-22 15:47
    关注

    I think the issue with your code is that when fetching the records from the database they are being returned as object and you are trying to use that object as if it was an array.

    You have 2 solutions, solution 1 is the most efficient:

    Solution 1: Use the variable $row as an object instead of an array

    foreach($table as $row) {
        fputcsv($handle, array( $row->id, $row->name, $row->phonenumber, $row->email,$row->umur, $row->tempattinggal,$row->bank, $row->kartukredit, $row->rumah,$row->keluarnegeri, $row->penghasilan ));
    }
    

    Solution 2: Convert the $row to an array for every loop

    foreach($table as $row) {
        $row = json_decode(json_encode($row), True);
        //Or $row = (array)$row;
        fputcsv($handle, array( $row['id'], $row['name'], $row['phonenumber'], $row['email'],$row['umur'], $row['tempattinggal'],$row['bank'], $row['kartukredit'], $row['rumah'],$row['keluarnegeri'], $row['penghasilan'] ));
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 spss统计中二分类变量和有序变量的相关性分析可以用kendall相关分析吗?
  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路
  • ¥15 公交车和无人机协同运输