Last active
November 16, 2019 04:53
-
-
Save syuji-higa/0a10579c62e981761c078d07787e762e to your computer and use it in GitHub Desktop.
PHP - CSV to map plus
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 | |
if($_SERVER['SERVER_NAME'] === 'xxxxx.xxx' && | |
(!isset($_SERVER['HTTP_X_REQUESTED_WITH']) || | |
$_SERVER['HTTP_X_REQUESTED_WITH'] !== 'XMLHttpRequest')) { | |
die(json_encode(array('status' => "Invalid call."))); | |
} | |
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) continue; | |
if($row_index === 1) { | |
foreach($line as $val) { | |
$keys[] = $val; | |
} | |
} else { | |
$arr = array(); | |
foreach($line as $col_index => $val) { | |
if($keys[$col_index] === 'view') { | |
if($val === '0') break; | |
} else { | |
$arr[$keys[$col_index]] = $val; | |
} | |
} | |
if(count($arr)) { | |
$map[] = $arr; | |
} | |
} | |
} | |
foreach($map as $key => $val) { | |
if(array_key_exists($key - 1, $map)) { | |
$map[$key]['prevId'] = $map[$key - 1]['id']; | |
} | |
if(array_key_exists($key + 1, $map)) { | |
$map[$key]['nextId'] = $map[$key + 1]['id']; | |
} | |
} | |
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); | |
header('Content-Type: application/json; charset=UTF-8'); | |
header('X-Content-Type-Options: nosniff'); | |
echo json_encode($data, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment