2

I want to export to a CSV a symfony entity. I have this code for the moment :

$em = $this->getDoctrine()->getEntityManager();

    $iterableResult = $em->getRepository('AppBundle:Member')
            ->createQueryBuilder('m')
            ->where('m.association = :id')
            ->setParameter('id', $id)
            ->getQuery()
            ->iterate();

    $handle = fopen('php://memory', 'r+');
    $header = array();

    while (false !== ($row = $iterableResult->next())) {
        dump($row[0]);
        fputcsv($handle, $row[0]);
        $em->detach($row[0]);
    }

    rewind($handle);
    $content = stream_get_contents($handle);
    fclose($handle);

    return new Response($content, 200, array(
        'Content-Type' => 'application/force-download',
        'Content-Disposition' => 'attachment; filename="export.csv"'
    ));

But I have this error :

Warning: fputcsv() expects parameter 2 to be array, object given

As you can see, I dump $row[0] for debug :

Member {#1360 ▼ -association: Association {#1444 ▶} -locality: Locality {#1421 ▶} -salutation: Salutation {#1409 ▶} -country: Country {#1454 ▶} -id: 844 -name: "TestName" -firstname: "TestFirstname" -date: DateTime {#1362 ▶} -email: "[email protected]" -phone: "123456789" -address: "Road 4, CH" -description: null }

I think the problem is because I have object in my object. What is the correct way to export an entity with object inside ?

Thanks

2 Answers 2

3

No, the problem is exactly what the warning says: fputcsv() expects the 2nd parameter to be an array and you're passing it an object (in this case, based on your dump output, an instance of Member)

To fix it you'd at the very least need to cast your object to an array

fputcsv($handle, (array) $row[0]);

Or implement something like Member::toArray() and use that

fputcsv($handle, $row[0]->toArray());

Or, implement a library that helps you do this like CSV from the PHP League.

Sign up to request clarification or add additional context in comments.

Comments

0

Finally, I have use the sonata-exporter bundle

It's work now

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.