Jump to content
cb2004

Create CSV of children, send file to user and delete file

Recommended Posts

Hi everybody, I hope you and your closest are staying safe.

I have potentially been staring at this a bit too long and have lost my train of thought. I have created a new action in admin using this hook (just in case it is useful to anybody) where I want to export the children to a CSV file (event participants):

<?php

$wire->addHookAfter('ProcessPageListRender::getPageActions(template=80)', function(HookEvent $event) {
	$page = $event->arguments[0];
	$actions = array();
	$actions['export'] = array(
		'cn'   => 'Export',
		'name' => 'Export',
		'url'  => $page->url.'export/',
	);
	if(count($actions)) $event->return = $actions + $event->return;
});

Here is then my code for the CSV:

if($input->urlSegment1 === 'export') {
    $array = $page->children->explode(function($item) {
        return array(
            'title' => $item->title,
        );
    });

    $fp = fopen("{$page->name}.csv", 'w');
    foreach ($array as $fields) fputcsv($fp, $fields);
    fclose($fp);
}

The CSV is getting created just fine, but how would I send this straight to the user (and then delete).

I know about Batch Child Editor and that is a fantastic module, I just wanted to create something quick (easy) but its consumed my brain cells for the last hour.

Cheers all.

Share this post


Link to post
Share on other sites
17 hours ago, cb2004 said:

The CSV is getting created just fine, but how would I send this straight to the user (and then delete).

A very similar problem was recently discussed here. Basically, you want to trigger a download by sending the following headers, then stream the file contents directly to the user and then kill the request:

header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="'.$page->name.'.csv"');

See the thread linked above for the complete example code. To stream the actual content you have to do a little bit of work since you are using fputcsv which expects a file handle. I see three approaches:

  1. Write the file like you are already doing, then use readfile to output it to the user, and then delete the file before closing the request (not so efficient).
  2. Just output the CSV string manually (might have to handle escaping the delimiters inside the CSV string yourself though).
  3. Open the file handle to "php://output", see here for details, or this comment on the fputcsv documentation.

Cheers!

  • Like 1

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

  • Recently Browsing   0 members

    No registered users viewing this page.

×
×
  • Create New...