CSVファイルを使用する
CSVファイルのデータを表示する
<html>
<head>
<title>CSVファイルのデータを表示する</title>
</head>
<body>
<?php
$fname = "test.csv";
$file = fopen($fname, "r");
while ($array = fgetcsv($file, 1000, ",")) {
echo "<hr>";
for ($i = 0; $i < count($array); $i++) {
echo $array[$i]."<br>";
}
}
fclose($file);
?>
</body>
</html>
項目が決まっているCSVファイルのデータを表示する
<html>
<head>
<title>項目が決まっているCSVファイルのデータを表示する</title>
</head>
<body>
<?php
$fname = "test.csv";
$file = fopen($fname, "r");
while (list($id, $name, $point) = fgetcsv($file, 1000, ",")) {
echo "<hr>";
echo "<br>ID:".$id;
echo "<br>名前:".$name;
echo "<br>点数:".$point;
}
fclose($file);
?>
</body>
</html>
CSVファイルにデータを書き込む
<html>
<head>
<title>CSVファイルにデータを書き込む</title>
</head>
<body>
<?php
$file_name = "test.csv";
$id = 999;
$name = "岡田";
$point = 90;
$array = compact("id", "name", "point");
$string = implode(",", $array);
echo "<p>CSVファイルにセットされるデータ:".$string;
$file = fopen($file_name, "a") or die("OPENエラー $file_name");
flock($file, LOCK_EX);
fputs($file, $string."\n");
flock($file, LOCK_UN);
fclose($file);
?>
</body>
</html>