file

(PHP 4, PHP 5, PHP 7, PHP 8)

fileReads entire file into an array

Опис

file(string $filename, int $flags = 0, ?resource $context = null): array|false

Reads an entire file into an array.

Зауваження:

You can use file_get_contents() to return the contents of a file as a string.

Параметри

filename

Path to the file.

Підказка

URL як назву файлу можна використовувати з цією функцією, якщо ввімкнені обгортки fopen. Докладніше про те, як вказати назву файлу: fopen(). На сторінці Підтримувані протоколи та обгортки є посилання на інформацію про можливості різних обгорток, примітки щодо їхнього використання, інформацію про будь-які попередньо визначені цими обгортками змінні.

flags

The optional parameter flags can be one, or more, of the following constants:

FILE_USE_INCLUDE_PATH
Search for the file in the include_path.
FILE_IGNORE_NEW_LINES
Omit newline at the end of each array element
FILE_SKIP_EMPTY_LINES
Skip empty lines
FILE_NO_DEFAULT_CONTEXT
Don't use the default context

context

resource контекст потоку.

Значення, що повертаються

Returns the file in an array. Each element of the array corresponds to a line in the file, with the newline still attached. Upon failure, file() returns false.

Зауваження:

Each line in the resulting array will include the line ending, unless FILE_IGNORE_NEW_LINES is used.

Зауваження: Якщо виникають проблеми з розпізнаванням закінчення рядків під час читання чи створення файлів на компʼютері Macintosh, може допомогти застосування директиви auto_detect_line_endings під час виконання.

Помилки/виключення

As of PHP 8.3.0, throws a ValueError if flags includes any invalid values, such as FILE_APPEND.

Emits an E_WARNING level error if the file does not exist.

Журнал змін

Версія Опис
8.3.0 ValueError is thrown for any invalid values of flags.

Приклади

Приклад #1 file() example

<?php
// Get a file into an array. In this example we'll go through HTTP to get
// the HTML source of a URL.
$lines = file('http://www.example.com/');

// Loop through our array, show HTML source as HTML source; and line numbers too.
foreach ($lines as $line_num => $line) {
echo
"Line #<b>{$line_num}</b> : " . htmlspecialchars($line) . "<br />\n";
}

// Using the optional flags parameter
$trimmed = file('somefile.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
?>

Примітки

Увага

Якщо використовувати SSL, Microsoft IIS порушуватиме протокол, закриваючи зʼєднання без надсилання індикатора close_notify. Коли буде досягнуто кінця даних, PHP повідомлятиме: "SSL: Fatal Protocol Error". Щоб обійти це, значення error_reporting має бути знижене до рівня, який не включає попереджень. PHP може виявити несправне програмне забезпечення сервера IIS та приховати попередження, якщо відкривати потік за допомогою обгортки https://. Якщо розробник використовує fsockopen() для створення сокета ssl://, то він сам має виявляти та приховувати це попередження.

Прогляньте також