FriendsOfCake / cakephp-csvview

CakePHP: A view class for generating CSV
MIT License
176 stars 64 forks source link

Example of a complex csv view file #114

Closed zipate closed 5 years ago

zipate commented 5 years ago

In the documentation it says "For really complex CSVs, you can also simply use your own view files". Could you kindly provide an example of how such view file would look like? I'm confused as to whether I'd have to print out the headers, separators and escape the data etc. manually

josegonzalez commented 5 years ago

You would have to print out your own headers etc. manually.

zipate commented 5 years ago

Thanks. Used solution below to manually generate csv file:

// app/Views/Posts/csv/index.ctp
$header = array('id' => '#', 'title' => 'Title', 'body' => 'Body', 'author' => 'Author(s)');

echo implode(',', $header)."\n"; // print header

foreach ($posts as $post):
    $row = [];
    foreach ($header as $key => $val) {
        if (array_key_exists($key, $post['Post'])) {
            $row[$key] = '"' . preg_replace('/"/','""',$application['Application'][$key]) . '"';
        } 
        elseif ($key == 'author') { //assuming post hasMany authors         
            foreach ($post['Author'] as $author) {
                (isset($row[$key])) ? $row[$key] .= '; '.$author['name'] : $row[$key] = $author['name'];
            }
            (isset($row[$key])) ? $row[$key] = '"' . preg_replace('/"/','""',$row[$key]) . '"' : $row[$key] = '""';
        } 
    }
    echo implode(',', $row) . "\n";
endforeach;