topic: file-io (read / write / CSV / paths / upload概念) / ch02 — ファイルを読む / 演習 01

📝 ドリル 01 — ファイル全体を読む

問題

__DIR__ . '/tests/data/hello.txt' の中身を そのまま標準出力に出す PHP を書いてください。

データファイル (tests/data/hello.txt):

こんにちは
ファイル読み込みのテスト

期待される出力:

こんにちは
ファイル読み込みのテスト

(末尾の改行はファイルに含まれている前提。echo で追加の "\n" を足さない)

採点

php scripts/grade.php topics/14-file-io/ch02-read-file/drill/01-read-all/

ヒント

$path = __DIR__ . '/tests/data/hello.txt';
echo file_get_contents($path);
▶ 3v4l で実行
  • file_get_contentsファイル全体を文字列で返す
  • 末尾の改行も含めて返すので、echo だけで OK
  • パスは __DIR__ 基準 で組む (cwd 依存にしない)

つまづいたら

  • Warning: file_get_contents(...): Failed to open stream → パスがズレている。__DIR__ . '/tests/data/hello.txt' の綴り / / の数を見直す
  • 末尾に空行が 1 つ余計に出る → echo file_get_contents($path) . "\n"; のように追加で改行を足していないか確認

テストケース

期待される出力

こんにちは
ファイル読み込みのテスト

📄 starter.php(雛形)

このコードから書き始めてください。

<?php

// TODO: tests/data/hello.txt のパスを __DIR__ ベースで組み立てる
// $path = __DIR__ . '/...';

// TODO: file_get_contents で中身を読んで echo する
// (末尾改行はファイルに含まれている前提。追加で "\n" を足さない)
✅ 解答例を見る(自分で解いてから)
<?php

// drill 内固定パスのファイルを丸ごと読んで出力する
$path = __DIR__ . '/tests/data/hello.txt';
echo file_get_contents($path);