Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Example of a complex csv view file #114

Closed
zipate opened this issue Sep 2, 2019 · 2 comments
Closed

Example of a complex csv view file #114

zipate opened this issue Sep 2, 2019 · 2 comments

Comments

@zipate
Copy link

zipate commented Sep 2, 2019

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
Copy link
Member

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

@zipate
Copy link
Author

zipate commented Sep 3, 2019

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;

@zipate zipate closed this as completed Sep 3, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

3 participants