[PHP]fgetcsvでCSVを読み込むサンプル

CSVファイル

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
1001,"yamda","東京"
2002,"user002","大阪"
1001,"yamda","東京" 2002,"user002","大阪"
1001,"yamda","東京"
2002,"user002","大阪"

使用例

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<?php
//読み込むcsvファイル
$filename = "C:\\study\\test.csv";
//ファイルの存在チェック
if (file_exists($filename)) {
csvReadFunc($filename);
} else {
print("file not exist");
}
//CSVを読み込む関数の定義
function csvReadFunc($filename)
{
//fopenでファイルを開く
$cft = fopen($filename, "r");
//csvを1行ずつ取得
while (($line = fgetcsv($cft, 1000, ","))) {
$result[] = $line;
}
//ファイルを閉じる
fclose($cft);
print($result[0][0]);
print($result[0][1]);
print($result[0][2]);
}
?>
<?php //読み込むcsvファイル $filename = "C:\\study\\test.csv"; //ファイルの存在チェック if (file_exists($filename)) { csvReadFunc($filename); } else { print("file not exist"); } //CSVを読み込む関数の定義 function csvReadFunc($filename) { //fopenでファイルを開く $cft = fopen($filename, "r"); //csvを1行ずつ取得 while (($line = fgetcsv($cft, 1000, ","))) { $result[] = $line; } //ファイルを閉じる fclose($cft); print($result[0][0]); print($result[0][1]); print($result[0][2]); } ?>
<?php
//読み込むcsvファイル
$filename = "C:\\study\\test.csv";

//ファイルの存在チェック
if (file_exists($filename)) {
  csvReadFunc($filename);
} else {
  print("file not exist");
}
//CSVを読み込む関数の定義
function csvReadFunc($filename)
{
  //fopenでファイルを開く
  $cft = fopen($filename, "r");
  //csvを1行ずつ取得
  while (($line = fgetcsv($cft, 1000, ","))) {
    $result[] = $line;
  }
  //ファイルを閉じる
  fclose($cft);

  print($result[0][0]); 
  print($result[0][1]); 
  print($result[0][2]); 
}
?>

結果
1001yamda東京

PHP

Posted by arkgame