PHP ファイル関連
ファイル操作、テキストファイル読み書きなどをやります。フォルダのファイル一覧取得
フォルダ内のファイル(フォルダ)一覧を取得するには、glob関数を使用します。引数にはパスを指定します。
ファイルだけ、またはフォルダだけに絞る場合は、is_dir関数、is_file関数を使用します。
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>PHP Test</title>
</head>
<body>
<?php
foreach (glob('C:/work/hp/sample/*') as $file) {
if (is_dir($file)) {
echo "フォルダ:" . $file . "<br>";
}
if (is_file($file)) {
echo "ファイル:" . $file . "<br>";
}
}
?>
</body>
</html>
ファイル読み込み
ファイルを読み込むには、file_get_contents関数またはfile関数を使用します。file_get_contents関数はファイルをそのまま取得し、file関数は取得したデータを配列に格納します。引数でパスを指定します。
file関数はオプションを渡していますが、それぞれ以下になります。
オプション | 説明 |
---|---|
FILE_IGNORE_NEW_LINES | 改行文字を付けない |
FILE_SKIP_EMPTY_LINES | 空行を無視する |
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>PHP Test</title>
</head>
<body>
<?php
$str = file_get_contents("C:/work/hp/sample/test1.txt");
$str = mb_convert_encoding($str, "UTF-8", "SJIS");
echo str_replace("\r\n", "<br />", $str);
$ary = file("C:/work/hp/sample/test1.txt", FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
foreach ($ary as $value) {
echo mb_convert_encoding($value, "UTF-8", "SJIS") . "<br />";
}
?>
</body>
</html>
ファイル書き込み
ファイルに書き込むには、file_put_contents関数を使用します。FILE_APPENDオプションを付けると、追記します。
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>PHP Test</title>
</head>
<body>
<?php
$str = "C:/work/hp/sample/test3.txt";
file_put_contents($str, "ファイル出力\r\n");
file_put_contents($str, "ファイル追記", FILE_APPEND);
$read = file_get_contents("C:/work/hp/sample/test1.txt");
echo str_replace("\r\n", "<br />", $read);
?>
</body>
</html>
フォルダ作成、ファイル、フォルダ存在チェック
フォルダ作成は、mkdir関数で行います。ファイル、フォロだの存在確認は、file_exists関数で行います。
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>PHP Test</title>
</head>
<body>
<?php
$dir = "C:/work/hp/sample/test";
mkdir($dir);
if (file_exists($dir)) {
echo "フォルダが作成されました";
}
?>
</body>
</html>
ページのトップへ戻る