Skip to content

Instantly share code, notes, and snippets.

@syuji-higa
Last active November 16, 2019 04:52
Show Gist options
  • Save syuji-higa/c47c182b22ebd4047aa4c118b39b1b7b to your computer and use it in GitHub Desktop.
Save syuji-higa/c47c182b22ebd4047aa4c118b39b1b7b to your computer and use it in GitHub Desktop.
PHP - search CSV view
<?php
setlocale(LC_ALL, 'ja_JP.UTF-8');
function get_csv_search_to_map($csv, $search_key, $search_val) {
$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();
$isIdLine = false;
$search_index = null;
foreach($file as $row_index => $line) {
if($row_index === 0) {
foreach($line as $kyes_index => $val) {
$keys[] = $val;
if($search_key === $val) {
$search_index = $kyes_index;
}
}
} else {
foreach($line as $col_index => $val) {
if($search_index === $col_index && $search_val === $val) {
$isIdLine = true;
}
if(!$isIdLine) continue;
$map[$keys[$col_index]] = $val;
}
if($isIdLine) break;
}
}
fclose($temp);
$file = null;
return $map;
}
if(!isset($_GET['id'])) exit;
$id = $_GET['id'];
$csv_data = file_get_contents('data.csv', "id,name,age\n0,taro,20,\n1,jiro,25,\n2,saburo,30");
$data = get_csv_search_to_map($csv_data, 'id', $id);
if(empty($data)) exit;
?>
<!DOCTYPE html>
<html lang="ja">
<body>
<li>ID: <?php echo $data['id'] ?></li>
<li>Name: <?php echo $data['name'] ?></li>
<li>Age: <?php echo $data['age'] ?></li>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment