file() 函數將文件內容按行讀入數組,每行作為一個元素(含換行符),適合逐行處理文本文件。
<?php
$DOCUMENT_ROOT = $_SERVER['DOCUMENT_ROOT'];
?>
<html>
<head>
<title>Test Array File</title>
</head>
<body>
<?php
$peoples = file($DOCUMENT_ROOT . '/test/03/people.txt');
$count = count($peoples);
if ($count == 0) {
echo 'NO peoples pending. Please try again later.';
} else {
for ($i = 0; $i < $count; $i++) {
echo $peoples[$i] . '<br />';
}
}
?>
</body>
</html>
file() 返回數組,單元包含行尾換行符,輸出時需注意array_map('trim', $arr) 去除首尾空白對比:fopen/fgets 逐行讀取內存佔用低,適合大文件;file_get_contents 讀整個文件為字符串;file() 直接得數組最便捷。