简体   繁体   English

csv export 调用数组上的成员函数fetch()

[英]csv export Call to a member function fetch() on array

Trying to create a simple CSV export function in symfony.尝试在 symfony 中创建一个简单的 CSV 导出功能。

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.但我收到“调用数组上的成员函数 fetch()”错误。

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).当我 print_r $stmt我肯定有一个数组,(它没有给出 PDO 错误)。 How do i either convert the array into an object or call the array so I can export it?我如何将数组转换为对象或调用数组以便导出它?

fetchAll already returns the array. fetchAll已经返回数组。 See Docs查看文档

So instead of using fetch again inside the while loop, You can simply loop through array.因此,您可以简单地循环遍历数组,而不是在while循环中再次使用fetch

//$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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM