public function actionExporturls() { $url = Yii::$app->request->get('url'); $search = Yii::$app->request->get('search'); $type = Yii::$app->request->get('type'); $model = new Webmeup(); $array = $model->respone($url, $type, $search); $f = fopen('php://output', 'w'); $firstLineKeys = false; $allArray = []; foreach ($array as $line) { $line = (array) $line; if (is_object(end($line))) { foreach ($line as $l) { $allArray[] = (array) $l; } break; } if (empty($firstLineKeys)) { $firstLineKeys = array_keys($line); fputcsv($f, $firstLineKeys); $firstLineKeys = array_flip($firstLineKeys); } // Using array_merge is important to maintain the order of keys acording to the first element fputcsv($f, array_merge($firstLineKeys, $line)); } if (!empty($allArray)) { foreach ($allArray as $line) { if (empty($firstLineKeys)) { $firstLineKeys = array_keys($line); fputcsv($f, $firstLineKeys); $firstLineKeys = array_flip($firstLineKeys); } // Using array_merge is important to maintain the order of keys acording to the first element fputcsv($f, array_merge($firstLineKeys, $line)); } } echo $f; Yii::$app->end(); }