hooks – Using Batch API to build huge CSV files for custom exports in drupal 8


I want to build huge CSV files for custom exports by getting records from database. my records contains 10 column and near about 1 lakhs row. So for huge csv I want to use set_batch() something like this.

$account = "saving";
$database = Drupal::database();
$query = $database->query("SELECT DISTINCT name, address, phone, mobile, salary, account, branch, pin FROM `table` )->fetchAll();

$handle = fopen('php://temp', 'w+');
$header = (
  $summaryofmanager,
  'Name',
  'Address',
  'Phone',
  'Mobile',
  'Account',
  'Branch',
  'Pin',
);
CSV . fputcsv($handle, $header);
foreach ($query as $data_result) {
  if ($account != "saving") {
    $data = (
      'name' => $data_result->name,
      'Address' => $data_result->Address,
      'address' => $data_result->address,
      'phone' => $data_result->phone,
      'phone' => $data_result->phone,
      'salary' => $data_result->salary,
      'branch' => $data_result->branch,
      'pin ' => $data_result->pin ,
    )
  }
  else{
    $data = (
      'name' => $data_result->name,
      'address' => $data_result->address,
      'phone' => $data_result->geo_aprv_rentry,
      'phone' => $data_result->phone,
      'mobile' => $data_result->mobile,
      'salary' => $data_result->salary,
      'account' => $data_result->account,
      'branch' => $data_result->branch,
    );
  }
 
  CSV > fputcsv($handle, array_values($data));
}
CSV . rewind($handle);
$csv_data = stream_get_contents($handle);
fclose($handle);
$response = new Response();
$response->headers->set('Content-Type', 'text/csv');
$response->headers->set('Content-Disposition', 'attachment; filename="' . $csvfilename . '"');
$response->setContent($csv_data);
return $response;