Summary of several methods for reading files in PHP (recommended), _ PHP Tutorial

Source: Internet
Author: User
Tags alphanumeric characters
Summary of several methods for reading files in PHP (recommended ),. Summary of several methods for reading files in PHP (recommended). 1. freadstringfread (int $ handle, int $ length) fread () reads a maximum of length bytes from the file pointed to by handle. Summary of several methods for this function to read files in PHP (recommended ),

1. fread

String fread (int $ handle, int $ length)

Fread () reads a maximum of length bytes from the file pointed to by handle. This function can be read by a maximum of length bytes, or when it reaches the EOF, or (for network streams) when a package is available, or (after opening the user space stream) when 8192 bytes have been read, the system stops reading files.

Fread () returns the read string. If an error occurs, FALSE is returned.

<? Php $ filename = "/usr/local/something.txt"; $ handle = fopen ($ filename, "r"); // when reading a binary file, you need to set the second parameter to 'RB' // Obtain the file size through filesize, and read the entire file into a string at once $ contents = fread ($ handle, filesize ($ filename); fclose ($ handle);?>

If the file to be read is not a local common file, but a remote file or stream file, this method cannot be used, because filesize cannot obtain the size of these files. In this case, you need to use the returned values of feof () or fread () to determine whether the object has been read to the end.

For example:

<?php  $handle = fopen('http://www.baidu.com', 'r');  $content = '';  while(!feof($handle)){    $content .= fread($handle, 8080);  }  echo $content;  fclose($handle);?>

Or:

<? Php $ handle = fopen ('http: // www.baidu.com ', 'r'); $ content = ''; while (false! = ($ A = fread ($ handle, 8080) {// Return false to indicate that the object has been read to the end of $ content. = $ a;} echo $ content; fclose ($ handle);?>

2. fgets

String fgets (int $ handle [, int $ length])

Fgets () reads a row from the file pointed to by handle and returns a string with a maximum length-1 bytes. When a line break (including the returned value), EOF, or the length-1 byte is read, it is stopped ). If length is not specified, the default value is 1 K, or 1024 bytes.

<?php  $handle = fopen('./file.txt', 'r');  while(!feof($handle)){    echo fgets($handle, 1024);  }  fclose($handle);?>

Note: The length parameter is optional since PHP 4.2.0. If this parameter is ignored, the row length is assumed to be 1024. Starting from PHP 4.3, ignoring length will continue to read data from the stream until the row ends. If most of the rows in the file are larger than 8 kB, it is more effective to specify the length of the maximum row in the script to use resources. Starting from PHP 4.3, this function can be safely used for binary files. Earlier versions do not work.

3. fgetss

String fgetss (resource $ handle [, int $ length [, string $ allowable_tags])

Similar to the fgets function, fgetss will try to remove any HTML and PHP tags from the read text. you can use the optional third parameter to specify which tags will not be removed.

<?php  $handle = fopen('./file.txt', 'r');  while(!feof($handle)){    echo fgetss($handle, 1024, '
'); } fclose($handle);?>

4. file

Array file (string $ filename [, int $ use_include_path [, resource $ context])

Read the file content into an array. each item in the array corresponds to a row in the file, including a line break. You can use the rtrim () function to filter line breaks when no line terminator is required.

<?php  $a = file('./file.txt');  foreach($a as $line => $content){    echo 'line '.($line + 1).':'.$content;  }?>

5. readfile

Int readfile (string $ filename [, bool $ use_include_path [, resource $ context])

Read a file and write it to the output buffer. Returns the number of bytes read from the file. If an error is returned, FALSE is returned, and the error message is displayed unless called in the form of @ readfile.

<?php  $size = readfile('./file.txt');  echo $size;?>

6. file_get_contents

String file_get_contents (string $ filename [, bool $ use_include_path [, resource $ context [, int $ offset [, int $ maxlen])

Reads a file into a string. The third parameter $ context can be used to set some parameters, such as setting timeout when accessing a remote file.

In addition, compared with the above functions, file_get_contents has a much better performance. Therefore, file_get_contents should be preferred. But readfile seems to have better performance than file_get_contents (?), Because it does not need to call fopen.

<? Php $ ctx = stream_context_create (array ('http' => array ('timeout' => 1 // set timeout); echo file_get_contents ("http://www.baidu.com/", 0, $ ctx);?>

7. fpassthru

Int fpassthru (resource $ handle)

Read the given file pointer from the current location to EOF and write the result to the output buffer.

<? Php header ("Content-Type: text/html; charset = utf-8"); $ handle = fopen ('. /test2.php ', 'r'); fseek ($ handle, 1024); // locate the pointer to fpassthru ($ handle) at the 1024 byte;?>

8. parse_ini_file

Array parse_ini_file (string $ filename [, bool $ process_sections])

Parse_ini_file () loads an ini file specified by filename and returns the settings as a union array. If the final process_sections parameter is set to TRUE, a multidimensional array is obtained, including the name and settings of each section in the configuration file. The default value of process_sections is FALSE.

Note:

1. if the value in the ini file contains any non-alphanumeric characters, enclose it in double quotation marks (").

2. some reserved words cannot be used as the key names in the ini file, including: null, yes, no, true, and false. The values are null, no and false are equivalent to "", and yes and true are equivalent to "1 ". Character {} | &~! [() "Cannot be used anywhere in the key name, and these characters have special meanings in the option value.

Content of the test. ini file:

; This is a sample configuration file; Comments start with ';', as in php.ini[first_section]one = 1five = 5animal = BIRD[second_section]path = "/usr/local/bin"URL = "http://www.example.com/~username

Test. php content:

<?php   $config = parse_ini_file('./test.ini', ture);  print_r($config);?>

Output Content:

Array(  [first_section] => Array    (      [one] => 1      [five] => 5      [animal] => BIRD    )  [second_section] => Array    (      [path] => /usr/local/bin      [URL] => http://www.example.com/~username    ))

Several notes:

1. encourage the use of the B flag when processing binary files, even if the system does not need it, this can make the script portability better.

2. the allow_url_fopen option activates the URL-based fopen encapsulation protocol to allow access to URL objects such as files. The default Encapsulation Protocol provides ftp and http protocols to access remote files. some extension libraries such as zlib may register more encapsulation protocols. For security reasons, this option can only be set in php. ini.

3. if you want to open a URL with special characters (such as spaces), you need to use urlencode () for URL encoding.

The above summary (recommended) of several methods for reading files in PHP is all the content shared by the editor. I hope to give you a reference and support for the help house.

Trim (recommended), 1. fread string fread (int $ handle, int $ length) fread () reads a maximum of length bytes from the file pointed to by handle. This function is in...

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.