CSV Exporter for ATK


#1

Hi!

I stumbled upon this add-on https://github.com/atk4/csv that was recently created (June, 2018) and the documentation for it looks very good! But sadly there doesn’t seem to be any sourcecode! Was this an oversight or is this add-on just a placeholder for a module that is yet to be written?

Cheers!
Len


#2

Hi @len and welcome to ATK.

Yes, the add-on spec seems to be quite cool and it’s on a roadmap sometime early next year (we’ll certainly need it for http://www.saasty.io), but for now you can use some variation of:

$fp = fopen('file.csv', 'w');
foreach ($model->export() as $row) {
    fputcsv($fp, $row);
}
fclose($fp);

#3

another one, thanks @zak for contributing!

    $csv = new \atk4\data\Persistence_CSV($csv_file_name);

    $model_export = new \atk4\data\Model($csv);

    if (!empty($fields_to_export)) {
        foreach ($fields_to_export as $export_field) {
            $model_export->addField($export_field);
        }
    } else {
        foreach ($this->elements as $element) {
            if ($element instanceof \atk4\Data\Field) {
                $model_export->addField($element->short_name);
            }
        }
    }

    // Convert and insert fields in CSV <
    foreach ($this as $row) {
        foreach ($fields_to_export as $export_field) {
            if ($row[$export_field] instanceof \DateTime) {
                $model_export[$export_field] = $row[$export_field]->format('M d, Y H:i:s');
            } else {
                $model_export[$export_field] = $row[$export_field];
            }
        }
        $model_export->save();
    }

    return $csv_file_name;