PHP code example of chrgriffin / collection-macro-csv
1. Go to this page and download the library: Download chrgriffin/collection-macro-csv library . Choose the download type require .
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
chrgriffin / collection-macro-csv example snippets
return [
// ...
'providers' => [
// ...
CollectionMacroCsv\ServiceProvider::class
]
];
$associativeArray = [
[
'name' => 'Geralt of Rivia',
'occupation' => 'Witcher'
],
[
'name' => 'Yennefer of Vengerberg',
'occupation' => 'Sorceress'
]
];
$csvArray = collect($associativeArray)->toCsvArray();
/*
* [
* ['name', 'occupation'],
* ['Geralt of Rivia', 'Witcher'],
* ['Yennefer of Vengerberg', 'Sorceress']
* ]
*/
$associativeArray = [
[
'name' => 'Geralt of Rivia',
'occupation' => 'Witcher'
],
[
'name' => 'Yennefer of Vengerberg',
'occupation' => 'Sorceress'
]
];
$csvString = collect($associativeArray)->toCsvString();
// name,occupation\nGeralt of Rivia,Witcher\nYennefer of Vengerberg,Sorceress
$csvString = collect($associativeArray)->toCsvString('|');
// name|occupation\nGeralt of Rivia|Witcher\nYennefer of Vengerberg|Sorceress
$associativeArray = [
[
'name' => 'Geralt of Rivia',
'occupation' => 'Witcher',
'witcher_school' => 'Wolf'
],
[
'name' => 'Yennefer of Vengerberg',
'occupation' => 'Sorceress',
'magic_speciality' => 'Portals'
]
];
$csvArray = collect($associativeArray)->toCsvArray();
/*
* [
* ['name', 'occupation', 'witcher_school', 'magic_speciality'],
* ['Geralt of Rivia', 'Witcher', 'Wolf', null],
* ['Yennefer of Vengerberg', 'Sorceress', null, 'Portals']
* ]
*/
$csvString = collect($associativeArray)->toCsvString();
// name,occupation,witcher_school,magic_speciality\nGeralt of Rivia,Witcher,Wolf,\nYennefer of Vengerberg,Sorceress,,Portals
$malformedArray = [
[
'name' => 'Geralt of Rivia',
'occupation' => 'Witcher',
'witcher_school' => 'Wolf'
],
'Yennefer of Vengerberg'
];
// throws a MalformedCollectionException
$csvArray = collect($malformedArray)->toCsvArray();