Skip to content

Instantly share code, notes, and snippets.

@helloworldlab
Forked from xavier83ar/ExampleController.php
Created September 15, 2023 15:03
Show Gist options
  • Select an option

  • Save helloworldlab/cb8a2dc5caafdcd5e2dc4b3bd108a426 to your computer and use it in GitHub Desktop.

Select an option

Save helloworldlab/cb8a2dc5caafdcd5e2dc4b3bd108a426 to your computer and use it in GitHub Desktop.
Export big data volumes. PHP + CakePHP (3-4) + CSV
<?php
/**
* Created by javier
* Date: 23/4/21
* Time: 18:35
*/
namespace App\Controller;
/**
* Class ExampleController
* @package App\Controller
*
* @property \Cake\ORM\Table Entities Ficticial table object
*/
class ExampleController extends AppController
{
/**
* @return \Cake\Http\Response
*/
public function downloadCsv()
{
// Prepare query
$query = $this->Entities->find();
// headers for the first line
$headers = [
'Field One',
'Field Two',
'Field Three',
];
$memFile = fopen('php://memory', 'w');
fputcsv($memFile, $headers);
// set a page limit, a greater limit, then more memory usage
$pageSize = 1000;
$total = $query->count();
$pages = intval(floor($total/$pageSize));
$page = 1;
$query
->limit($pageSize)
->page($page);
$entities = $query->all();
while ($entities->count() > 0) {
foreach ($entities as $entity) {
$datos = [
$entity->field_one,
$entity->field_two,
$entity->field_three,
];
fputcsv($memFile, $datos);
}
if ($page > $pages) {
break;
}
$query
->clearResult() // reset query results
->page($page++); // set next page
$entities = $query->all();
}
rewind($memFile);
$content = stream_get_contents($memFile);
fclose($memFile);
return $this->response
->withStringBody($content)
->withDownload('exported-data.csv');
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment