Skip to content

Instantly share code, notes, and snippets.

@orleika
Last active September 19, 2017 10:13
Show Gist options
  • Save orleika/800165ffe212d81bf417a6d349cdb1bf to your computer and use it in GitHub Desktop.
Save orleika/800165ffe212d81bf417a6d349cdb1bf to your computer and use it in GitHub Desktop.
csv file utilities with laravel
<?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