Last active
November 16, 2019 04:52
-
-
Save syuji-higa/c39b007df91bcc20ee418c346212b85f to your computer and use it in GitHub Desktop.
PHP - CSV to map
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 | |
setlocale(LC_ALL, 'ja_JP.UTF-8'); | |
function csv_to_map($csv) { | |
$csv = ereg_replace("\r\n|\r|\n", "\n", $csv); | |
$csv = mb_convert_encoding($csv, 'UTF-8', 'sjis-win'); | |
$temp = tmpfile(); | |
$meta = stream_get_meta_data($temp); | |
fwrite($temp, $csv); | |
rewind($temp); | |
$file = new SplFileObject($meta['uri']); | |
$file -> setFlags(SplFileObject::READ_CSV); | |
$map = array(); | |
$keys = array(); | |
foreach($file as $row_index => $line) { | |
if($row_index === 0) { | |
foreach($line as $val) { | |
$keys[] = $val; | |
} | |
} else { | |
$arr = array(); | |
foreach($line as $col_index => $val) { | |
$arr[$keys[$col_index]] = $val; | |
} | |
$map[] = $arr; | |
} | |
} | |
fclose($temp); | |
$file = null; | |
return $map; | |
} | |
$csv_data = file_get_contents('data.csv', "id,name,age\n0,taro,20,\n1,jiro,25,\n2,saburo,30"); | |
$data = csv_to_map($csv_data); | |
var_dump($data); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment