Home  >  Article  >  Backend Development  >  How to use php file_get_contents function

How to use php file_get_contents function

藏色散人
藏色散人Original
2019-05-25 10:29:214931browse

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(&#39;http://www.example.com/&#39;);
echo $homepage;
?>

Read a part of the file

<?php
// Read 14 characters starting from the 21st character
$section = file_get_contents(&#39;./people.txt&#39;, NULL, NULL, 20, 14);
var_dump($section);
?>

In the included Search in path

<?php
// <= PHP 5
$file = file_get_contents(&#39;./people.txt&#39;, true);
// > PHP 5
$file = file_get_contents(&#39;./people.txt&#39;, FILE_USE_INCLUDE_PATH);
?>

Use context

<?php
// Create a stream
$opts = array(
  &#39;http&#39;=>array(
    &#39;method&#39;=>"GET",
    &#39;header&#39;=>"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(&#39;http://www.example.com/&#39;, 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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn