/** * batch export product * @param integer $id * @return mixed */ public function actionExport() { //if(!Yii::$app->user->can('viewYourAuth')) throw new ForbiddenHttpException(Yii::t('app', 'No Auth')); $format = Product::getImportExportFormat(); $products = Product::find()->orderBy(['id' => SORT_ASC])->all(); $str = ''; // 生成csv标题行 $product = new Product(); $start = true; foreach ($format as $column) { if ($start) { $str .= '"' . iconv('utf-8', 'gb2312', $product->attributeLabels()[$column]) . '"'; $start = false; } else { $str .= ',"' . iconv('utf-8', 'gb2312', $product->attributeLabels()[$column]) . '"'; } } $str .= ',' . iconv('utf-8', 'gb2312', Yii::t('app', 'Thumbs')) . ',' . iconv('utf-8', 'gb2312', Yii::t('app', 'Images')); $str .= "\n"; foreach ($products as $row) { // 导出 product表中的数据 $start = true; foreach ($format as $column) { $value = ''; if ($column == 'category_id') { if ($row[$column] > 0) { $category = Category::findOne($row[$column]); $value = iconv('utf-8', 'gb2312', $category->name); } } elseif ($column == 'brand_id') { if ($row[$column] > 0) { $brand = Brand::findOne($row[$column]); $value = iconv('utf-8', 'gb2312', $brand->name); } } else { $value = iconv('utf-8', 'gb2312', $row[$column]); } if ($start) { $str .= '"' . $value . '"'; $start = false; } else { $str .= ',"' . str_replace("\"", "\"\"", $value) . '"'; } } // 导出product_image表中的数据 $start = true; $strThumb = $strImage = ''; $productImages = ProductImage::find()->where(['product_id' => $row->id])->all(); foreach ($productImages as $item) { if ($start) { $strThumb .= $item->thumb; $strImage .= $item->image; $start = false; } else { $strThumb .= '|' . $item->thumb; $strImage .= '|' . $item->image; } } $str .= ',"' . $strThumb . '","' . $strImage . '"'; $str .= "\n"; } $filename = date('Ymd') . '.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 $str; }