Home >Backend Development >PHP Problem >How to use php file_get_contents function
How to use the php file_get_contents function?
Function: Read the entire file into a string.
Syntax:
file_get_contents ( string $filename [, bool $use_include_path = false [, resource $context [, int $offset = -1 [, int $maxlen ]]]] ) : string
The preferred method for reading the contents of a file into a string. If supported by the operating system, memory mapping technology is also used to enhance performance.
Parameters:
filename | The name of the file to be read. |
use_include_path | In PHP 5, FILE_USE_INCLUDE_PATH can be used to trigger include path searches. |
context |
A valid context resource created using stream_context_create(). If you don’t need to customize the context, you can use NULL to ignore it. |
offset |
Read the offset starting on the original stream. Remote files do not support lookup (offset). Trying to find on a non-local file may use a smaller offset, but this is unpredictable since it works on a buffered stream. |
maxlen | The maximum length of read data. The default reading method is to read to the end of the file. Note that this parameter applies to streams processed by the filter. |
Return value:
The function returns the data read or returns FALSE on failure.
php file_get_contents() function usage example
Get the website homepage
<?php $homepage = file_get_contents('http://www.example.com/'); echo $homepage; ?>
Read a part of the file
<?php // Read 14 characters starting from the 21st character $section = file_get_contents('./people.txt', NULL, NULL, 20, 14); var_dump($section); ?>
In the included Search in path
<?php // <= PHP 5 $file = file_get_contents('./people.txt', true); // > PHP 5 $file = file_get_contents('./people.txt', FILE_USE_INCLUDE_PATH); ?>
Use context
<?php // Create a stream $opts = array( 'http'=>array( 'method'=>"GET", 'header'=>"Accept-language: en\r\n" . "Cookie: foo=bar\r\n" ) ); $context = stream_context_create($opts); // Open the file using the HTTP headers set above $file = file_get_contents('http://www.example.com/', false, $context); ?>
The above is the detailed content of How to use php file_get_contents function. For more information, please follow other related articles on the PHP Chinese website!