Reputation: 2962
Trying to create a simple CSV export function in symfony.
Using the following code
/**
* @Route("/csv", name="csv_output")
* @Method("GET")
*/
public function exportCSV()
{
$stmt = $this->getDoctrine()->getRepository(Work::class)->csvOutput();
$csv = fopen('php://output', 'w');
while ($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
fputcsv($csv, $row);
}
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename=coursenames.csv');
fclose($csv);
}
but am getting a "Call to a member function fetch() on array" error.
The query is this:
public function csvOutput()
{
$em = $this->getEntityManager();
$all = ("SELECT
w.id,
w.title,
w.description,
c.name AS CLIENT,
t.name AS TYPE,
f.name AS FORMAT,
p.name AS platform,
w.notes,
w.pub_url,
w.priv_url,
w.ghost_ind,
w.net_pay,
w.hours,
w.hourly,
w.date_submitted,
w.date_published,
w.work_type
FROM WORK
w
LEFT JOIN CLIENT c ON
w.client_id_id = c.id
LEFT JOIN TYPE t ON
w.type_id = t.id
LEFT JOIN FORMAT f ON
w.format_id = f.id
LEFT JOIN platform p ON
w.platform_id = p.id");
$stmt = $em->getConnection()->prepare($all);
$stmt->execute();
return $stmt->fetchAll();
}
When I print_r $stmt
I definitely have an array there, (it's not giving a PDO error). How do i either convert the array into an object or call the array so I can export it?
Upvotes: 0
Views: 94
Reputation: 3476
fetchAll
already returns the array. See Docs
So instead of using fetch
again inside the while
loop, You can simply loop through array.
//$stmt = $this->getDoctrine()->getRepository(Work::class)->csvOutput();
$rows = $this->getDoctrine()->getRepository(Work::class)->csvOutput(); //Use $rows as returned array.
$csv = fopen('php://output', 'w');
//Comment while loop and replace with foreach.
//while ($row = $stmt->fetch(PDO::FETCH_ASSOC))
//{
foreach( $rows as $row ) {
fputcsv($csv, $row);
}
Upvotes: 1