Đang chuẩn bị nút TẢI XUỐNG, xin hãy chờ
Tải xuống
Các tập tin () chức năng có khả năng đọc một tập tin vào một mảng, tách từng phần tử bằng cách ký tự dòng mới, với các dòng mới vẫn thuộc phần cuối của mỗi phần tử. Nguyên mẫu của nó sau: mảng tập tin (string filename [int use_include_path [, bối cảnh tài nguyên]]) | 290 CHAPTER 10 WORKING WITH THE FILE AND OPERATING SYSTEM Reading a File into an Array The file function is capable of reading a file into an array separating each element by the newline character with the newline still attached to the end of each element. Its prototype follows array file string filename int use_include_path resource context Although simplistic the importance of this function can t be overstated and therefore it warrants a simple demonstration. Consider the following sample text file named users.txt Ale ale@example.com Nicole nicole@example.com Laura laura@example.com The following script reads in users.txt and parses and converts the data into a convenient Web-based format. Notice file provides special behavior because unlike other read write functions you don t have to establish a file handle in order to read it php Read the file into an array users file users.txt Cycle through the array foreach users as user Parse the line retrieving the name and e-mail address list name email explode user Remove newline from email email trim email Output the formatted name and e-mail address echo a href mailto email name a br CHAPTER 10 WORKING WITH THE FILE AND OPERATING SYSTEM 291 This script produces the following HTML output a href ale@example.com Ale a br a href nicole@example.com Nicole a br a href laura@example.com Laura a br Like fopen you can tell file to search through the paths specified in the include_path configuration parameter by setting use_include_path to 1. The context parameter refers to a stream context. You ll learn more about this topic in Chapter 16. Reading File Contents into a String Variable The file_get_contents function reads the contents of a file into a string. Its prototype follows string file_get_contents string filename int use_include_path resource context By revising the script from the preceding section to use this function instead of file you get the following code php Read the file into a string variable userfile .