Read CSV File

Don’t use phpspreadsheet to read .csv file because there could be some bugs and get incorrect result.

    private function get_value($row, $index){
        $value = mb_convert_encoding($row[$index], 'UTF-8', 'Big5');
        $value = str_replace('\'', '', $value);
        $value = trim($value);
        return $value;
    }

    public function import(Request $req){
        $file = $req->file('file');
        //logg($file->getClientOriginalName());

        $file_name = 'import_shipping_orders.csv';
        $dest = storage_path('app');
        $file->move($dest, $file_name);
        $file_path = $dest . '/' . $file_name;
        //logg($dest);

        $row_index = 1;
        $debug = false;
        if (($handle = fopen($file_path, "r")) !== FALSE) {
            while (($row = fgetcsv($handle, 1000, ",")) !== FALSE) {
                if($row_index == 1){
                    if($debug == true){
                        foreach ($row as $key => $value) {
                            echo $this->get_value($row, $key) . '<br/>';
                        }
                        exit();
                    }

                    $row_index++;
                    continue;
                }

                $order_no = $this->get_value($row, 2);
                if($order_no == false){
                    echo 'Row ' . $row_index . ' has no order no.<br/>';
                    continue;
                }

                $order = OrderM::where('order_no', $order_no)->first();
                if($order == false){
                    echo 'Row ' . $row_index . ' has no matched order.<br/>';
                    continue;
                }

                $order->process_status = 1;
                $order->ship_date = $this->get_value($row, 0);
                $order->est_date = $this->get_value($row, 1);
                $order->ship_no = $this->get_value($row, 3);
                $order->ship_note = $this->get_value($row, 6);
                $order->save();
                
                echo 'Row ' . $row_index . ' is updated successfully.<br/>';
                $row_index++;
            }
            fclose($handle);
        }

        echo 'Done';
    }

Reference:

  1. https://www.php.net/manual/zh/function.fgetcsv