Last active
September 19, 2017 10:13
-
-
Save orleika/800165ffe212d81bf417a6d349cdb1bf to your computer and use it in GitHub Desktop.
csv file utilities with laravel
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App\Http\Middleware; | |
use Response; | |
use Exception; | |
class CSV | |
{ | |
/** | |
* downlaod csv file | |
* @param string $csv_text csv-like text | |
* @param string $filename | |
* @return \Illuminate\Http\Response | |
*/ | |
public static function download($csv_text, $filename = 'document.csv') | |
{ | |
$stream = fopen('php://temp', 'r+b'); | |
fwrite($stream, $csv_text); | |
rewind($stream); | |
$csv = str_replace(PHP_EOL, "\r\n", stream_get_contents($stream)); | |
fclose($stream); | |
// $csv = mb_convert_encoding($csv, 'SJIS-win', 'UTF-8'); | |
$headers = array( | |
'Content-Type' => 'text/csv', | |
'Content-Disposition' => "attachment; filename=$filename", | |
); | |
return Response::make($csv, 200, $headers); | |
} | |
/** | |
* parse csv-like text | |
* @param string $csv_text csv-like text | |
* @return \Illuminate\Support\Collection | |
*/ | |
public static function parse($csv_text) | |
{ | |
$lines = collect(array_map('trim', explode("\n", $csv_text))); | |
$headers = collect(explode(',', $lines->first())); | |
$body = $lines | |
->slice(1) | |
->map(function($item) { | |
if (!trim($item)) { | |
return []; | |
} | |
return explode(',', $item); | |
}) | |
->filter(); | |
$combined = $body->map(function($item) use ($headers) { | |
if ($headers->count() !== count($item)) { | |
throw new Exception("Mismatch headers and body size."); | |
} | |
return $headers->combine($item); | |
}); | |
return $combined; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment