{"id":13684608,"url":"https://github.com/FriendsOfCake/cakephp-csvview","last_synced_at":"2025-05-01T00:32:07.783Z","repository":{"id":4676618,"uuid":"5823079","full_name":"FriendsOfCake/cakephp-csvview","owner":"FriendsOfCake","description":"CakePHP: A view class for generating CSV","archived":false,"fork":false,"pushed_at":"2024-01-02T18:19:12.000Z","size":290,"stargazers_count":176,"open_issues_count":3,"forks_count":64,"subscribers_count":15,"default_branch":"5.x","last_synced_at":"2024-10-30T01:03:18.897Z","etag":null,"topics":["cakephp","cakephp-plugin","csv","php"],"latest_commit_sha":null,"homepage":"","language":"PHP","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/FriendsOfCake.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":"CONTRIBUTING.md","funding":null,"license":"LICENSE.txt","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2012-09-15T18:54:32.000Z","updated_at":"2024-09-19T02:38:44.000Z","dependencies_parsed_at":"2024-06-18T12:23:16.639Z","dependency_job_id":"8b9d54f7-abff-4516-a8e0-7ce085b331fe","html_url":"https://github.com/FriendsOfCake/cakephp-csvview","commit_stats":{"total_commits":244,"total_committers":34,"mean_commits":7.176470588235294,"dds":0.7049180327868853,"last_synced_commit":"82f5379d42ddecf4454b27c8276f4962c275481a"},"previous_names":[],"tags_count":23,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/FriendsOfCake%2Fcakephp-csvview","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/FriendsOfCake%2Fcakephp-csvview/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/FriendsOfCake%2Fcakephp-csvview/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/FriendsOfCake%2Fcakephp-csvview/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/FriendsOfCake","download_url":"https://codeload.github.com/FriendsOfCake/cakephp-csvview/tar.gz/refs/heads/5.x","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":224204084,"owners_count":17273046,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["cakephp","cakephp-plugin","csv","php"],"created_at":"2024-08-02T14:00:35.549Z","updated_at":"2024-11-12T06:30:20.571Z","avatar_url":"https://github.com/FriendsOfCake.png","language":"PHP","readme":"[![CI](https://github.com/FriendsOfCake/cakephp-csvview/actions/workflows/ci.yml/badge.svg)](https://github.com/FriendsOfCake/cakephp-csvview/actions/workflows/ci.yml)\n[![Coverage Status](https://img.shields.io/codecov/c/github/FriendsOfCake/cakephp-csvview.svg?style=flat-square)](https://codecov.io/gh/FriendsOfCake/cakephp-csvview)\n[![Total Downloads](https://img.shields.io/packagist/dt/friendsofcake/cakephp-csvview.svg?style=flat-square)](https://packagist.org/packages/friendsofcake/cakephp-csvview)\n[![Latest Stable Version](https://img.shields.io/packagist/v/friendsofcake/cakephp-csvview.svg?style=flat-square)](https://packagist.org/packages/friendsofcake/cakephp-csvview)\n[![Software License](https://img.shields.io/badge/license-MIT-brightgreen.svg?style=flat-square)](LICENSE.txt)\n\n# CsvView Plugin\n\nQuickly enable CSV output of your model data.\n\nThis branch is for CakePHP **5.x**. For details see [version map](https://github.com/FriendsOfCake/cakephp-csvview/wiki#cakephp-version-map).\n\n## Background\n\nI needed to quickly export CSVs of stuff in the database. Using a view class to\niterate manually would be a chore to replicate for each export method, so I\nfigured it would be much easier to do this with a custom view class,\nlike JsonView or XmlView.\n\n## Installation\n\n```\ncomposer require friendsofcake/cakephp-csvview\n```\n\n### Enable plugin\n\nLoad the plugin by running command\n\n    bin/cake plugin load CsvView\n\n## Usage\n\nTo export a flat array as a CSV, one could write the following code:\n\n```php\npublic function export()\n{\n    $data = [\n        ['a', 'b', 'c'],\n        [1, 2, 3],\n        ['you', 'and', 'me'],\n    ];\n\n    $this-\u003eset(compact('data'));\n    $this-\u003eviewBuilder()\n        -\u003esetClassName('CsvView.Csv')\n        -\u003esetOption('serialize', 'data');\n}\n```\n\nAll variables that are to be included in the csv must be specified in the\n`serialize` view option, exactly how `JsonView` or `XmlView` work.\n\nIt is possible to have multiple variables in the csv output:\n\n```php\npublic function export()\n{\n    $data = [['a', 'b', 'c']];\n    $data_two = [[1, 2, 3]];\n    $data_three = [['you', 'and', 'me']];\n\n    $serialize = ['data', 'data_two', 'data_three'];\n\n    $this-\u003eset(compact('data', 'data_two', 'data_three'));\n    $this-\u003eviewBuilder()\n        -\u003esetClassName('CsvView.Csv')\n        -\u003esetOption('serialize', $serialize);\n}\n```\n\nIf you want headers or footers in your CSV output, you can specify either a\n`header` or `footer` view option. Both are completely optional:\n\n```php\npublic function export()\n{\n    $data = [\n        ['a', 'b', 'c'],\n        [1, 2, 3],\n        ['you', 'and', 'me'],\n    ];\n\n    $header = ['Column 1', 'Column 2', 'Column 3'];\n    $footer = ['Totals', '400', '$3000'];\n\n    $this-\u003eset(compact('data'));\n    $this-\u003eviewBuilder()\n        -\u003esetClassName('CsvView.Csv')\n        -\u003esetOptions([\n            'serialize' =\u003e 'data',\n            'header' =\u003e $header,\n            'footer' =\u003e $footer,\n        ]);\n}\n```\n\nYou can also specify the delimiter, end of line, newline, escape characters and\nbyte order mark (BOM) sequence using `delimiter`, `eol`, `newline`, `enclosure`\nand `bom` respectively:\n\n```php\npublic function export()\n{\n    $data = [\n        ['a', 'b', 'c'],\n        [1, 2, 3],\n        ['you', 'and', 'me'],\n    ];\n\n    $this-\u003eset(compact('data'));\n    $this-\u003eviewBuilder()\n        -\u003esetClassName('CsvView.Csv')\n        -\u003esetOptions([\n            'serialize' =\u003e 'data',\n            'delimiter' =\u003e chr(9),\n            'enclosure' =\u003e '\"',\n            'newline' =\u003e '\\r\\n',\n            'eol' =\u003e '~',\n            'bom' =\u003e true,\n        ]);\n}\n```\n\nThe defaults for these options are:\n\n* `delimiter`: `,`\n* `enclosure`: `\"`\n* `newline`: `\\n`\n* `eol`: `\\n`\n* `bom`: false\n* `setSeparator`: false\n\nThe `eol` option is the one used to generate newlines in the output.\n`newline`, however, is the character that should replace the newline characters\nin the actual data. It is recommended to use the string representation of the\nnewline character to avoid rendering invalid output.\n\nSome reader software incorrectly renders UTF-8 encoded files which do not\ncontain byte order mark (BOM) byte sequence. The `bom` option is the one used\nto add byte order mark (BOM) byte sequence beginning of the generated CSV output\nstream. See [`Wikipedia article about byte order mark`](http://en.wikipedia.org/wiki/Byte_order_mark)\nfor more information.\n\nThe `setSeparator` option can be used to set the separator explicitly in the\nfirst line of the CSV. Some readers need this in order to display the CSV correctly.\n\nIf you have complex model data, you can use the `extract` view option to\nspecify the individual [`Hash::extract()`-compatible](http://book.cakephp.org/4/en/core-libraries/hash.html) paths\nor a callable for each record:\n\n```php\npublic function export()\n{\n    $posts = $this-\u003ePosts-\u003efind();\n    $header = ['Post ID', 'Title', 'Created'];\n    $extract = [\n        'id',\n        function (array $row) {\n            return $row['title'];\n        },\n        'created'\n    ];\n\n    $this-\u003eset(compact('posts'));\n    $this-\u003eviewBuilder()\n        -\u003esetClassName('CsvView.Csv')\n        -\u003esetOptions([\n            'serialize' =\u003e 'posts',\n            'header' =\u003e $header,\n            'extract' =\u003e $extract,\n        ]);\n}\n```\n\nIf your model data contains some null values or missing keys, you can use the\n`null` option, just like you'd use `delimiter`, `eol`, and `enclosure`,\nto set how null values should be displayed in the CSV.\n\n`null` defaults to `''`.\n\n#### Automatic view class switching\n\nYou can use the controller's content negotiation feature to automatically have\nthe CsvView class switched in as follows.\n\nEnable `csv` extension parsing using `$routes-\u003eaddExtensions(['csv'])` within required\nscope in your app's `routes.php`.\n\n```php\n// PostsController.php\n\n// Add the CsvView class for content type negotiation\npublic function initialize(): void\n{\n    parent::initialize();\n\n    $this-\u003eaddViewClasses(['csv' =\u003e 'CsvView.Csv']);\n}\n\n// Controller action\npublic function index()\n{\n    $posts = $this-\u003ePosts-\u003efind();\n    $this-\u003eset(compact('posts'));\n\n    if ($this-\u003erequest-\u003eis('csv')) {\n        $serialize = 'posts';\n        $header = array('Post ID', 'Title', 'Created');\n        $extract = array('id', 'title', 'created');\n\n        $this-\u003eviewBuilder()-\u003esetOptions(compact('serialize', 'header', 'extract'));\n    }\n}\n```\n\nWith the above controller you can now access `/posts.csv` or use `Accept` header\n`text/csv` to get the data as csv and use `/posts` to get normal HTML page.\n\nFor really complex CSVs, you can also use your own view files. To do so, either\nleave `serialize` unspecified or set it to null. The view files will be located\nin the `csv` subdirectory of your current controller:\n\n```php\n// View used will be in templates/Posts/csv/export.php\npublic function export()\n{\n    $posts = $this-\u003ePosts-\u003efind();\n    $this-\u003eset(compact('posts'));\n    $this-\u003eviewBuilder()\n        -\u003esetClassName('CsvView.Csv')\n        -\u003esetOption('serialize', null);\n}\n```\n\n#### Setting a different encoding to the file\n\nIf you need to have a different encoding in you csv file you have to set the\nencoding of your data you are passing to the view and also set the encoding you\nwant for the csv file. This can be done by using `dataEncoding` and `csvEncoding`:\n\nThe defaults are:\n\n* `dataEncoding`: `UTF-8`\n* `csvEncoding`: `UTF-8`\n\n** Only if those two variable are different your data will be converted to another encoding.\n\nCsvView uses the `iconv` extension by default to encode your data. You can change\nthe php extension used to encode your data by setting the `transcodingExtension` option:\n\n```php\n$this-\u003eviewBuilder()-\u003esetOption('transcodingExtension', 'mbstring');\n```\n\nThe currently supported encoding extensions are as follows:\n\n- `iconv`\n- `mbstring`\n\n#### Setting the downloaded file name\n\nBy default, the downloaded file will be named after the last segment of the URL\nused to generate it. Eg: `example.com/my-controller/my-action` would download\n`my-action.csv`, while `example.com/my-controller/my-action/first-param` would\ndownload `first-param.csv`.\n\n\u003e In IE you are required to set the filename, otherwise it will download as a text file.\n\nTo set a custom file name, use the `Response::withDownload()` method. The following\nsnippet can be used to change the downloaded file from `export.csv` to `my-file.csv`:\n\n```php\npublic function export()\n{\n    $data = [\n        ['a', 'b', 'c'],\n        [1, 2, 3],\n        ['you', 'and', 'me'],\n    ];\n\n    $this-\u003esetResponse($this-\u003egetResponse()-\u003ewithDownload('my-file.csv'));\n    $this-\u003eset(compact('data'));\n    $this-\u003eviewBuilder()\n        -\u003esetClassName('CsvView.Csv')\n        -\u003esetOption('serialize', 'data');\n}\n```\n\n#### Using a specific View Builder\n\nIn some cases, it is better not to use the current controller's View Builder\n`$this-\u003eviewBuilder()` as any call to `$this-\u003erender()` will compromise any\nsubsequent rendering.\n\nFor example, in the course of your current controller's action, if you need to\nrender some data as CSV in order to simply save it into a file on the server.\n\nDo not forget to add to your controller:\n\n```php\nuse Cake\\View\\ViewBuilder;\n```\nSo you can create a specific View Builder:\n\n```php\n// Your data array\n$data = [];\n\n// Options\n$serialize = 'data';\n$delimiter = ',';\n$enclosure = '\"';\n$newline = '\\r\\n';\n\n// Create the builder\n$builder = new ViewBuilder();\n$builder\n    -\u003esetLayout(false)\n    -\u003esetClassName('CsvView.Csv')\n    -\u003esetOptions(compact('serialize', 'delimiter', 'enclosure', 'newline'));\n\n// Then the view\n$view = $builder-\u003ebuild($data);\n$view-\u003eset(compact('data'));\n\n// And Save the file\nfile_put_contents('/full/path/to/file.csv', $view-\u003erender());\n```\n\n","funding_links":[],"categories":["Templating"],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2FFriendsOfCake%2Fcakephp-csvview","html_url":"https://awesome.ecosyste.ms/projects/github.com%2FFriendsOfCake%2Fcakephp-csvview","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2FFriendsOfCake%2Fcakephp-csvview/lists"}