mirror of
https://github.com/php/doc-ru.git
synced 2025-07-24 09:59:46 +00:00
269 lines
9.6 KiB
XML
269 lines
9.6 KiB
XML
<?xml version="1.0" encoding="utf-8"?>
|
||
<!-- EN-Revision: a9a6224ca97531df0a4e4b9b16b59c3f2baf1b09 Maintainer: shein Status: ready -->
|
||
<!-- Reviewed: yes -->
|
||
<!-- $Revision$ -->
|
||
<refentry xmlns="http://docbook.org/ns/docbook" xml:id="function.file-get-contents" xmlns:xlink="http://www.w3.org/1999/xlink">
|
||
<refnamediv>
|
||
<refname>file_get_contents</refname>
|
||
<refpurpose>Читает содержимое файла в строку</refpurpose>
|
||
</refnamediv>
|
||
|
||
<refsect1 role="description">
|
||
&reftitle.description;
|
||
<methodsynopsis>
|
||
<type class="union"><type>string</type><type>false</type></type><methodname>file_get_contents</methodname>
|
||
<methodparam><type>string</type><parameter>filename</parameter></methodparam>
|
||
<methodparam choice="opt"><type>bool</type><parameter>use_include_path</parameter><initializer>&false;</initializer></methodparam>
|
||
<methodparam choice="opt"><type>resource</type><parameter>context</parameter></methodparam>
|
||
<methodparam choice="opt"><type>int</type><parameter>offset</parameter><initializer>0</initializer></methodparam>
|
||
<methodparam choice="opt"><type>int</type><parameter>maxlen</parameter></methodparam>
|
||
</methodsynopsis>
|
||
<para>
|
||
Данная функция похожа на функцию <function>file</function> с той лишь
|
||
разницей, что <function>file_get_contents</function> возвращает
|
||
содержимое файла в строке, начиная с указанного смещения
|
||
<parameter>offset</parameter> и до <parameter>maxlen</parameter>
|
||
байт. В случае неудачи, <function>file_get_contents</function> вернёт &false;.
|
||
</para>
|
||
<para>
|
||
Использование функции <function>file_get_contents</function>
|
||
наиболее предпочтительно в случае необходимости получить
|
||
содержимое файла целиком, поскольку для улучшения производительности
|
||
функция использует технику отображения файла в память
|
||
(memory mapping), если она поддерживается вашей операционной системой.
|
||
</para>
|
||
<note>
|
||
<para>
|
||
Если вы открываете URI, содержащий спецсимволы, такие как пробел,
|
||
вам нужно закодировать URI при помощи <function>urlencode</function>.
|
||
</para>
|
||
</note>
|
||
</refsect1>
|
||
|
||
<refsect1 role="parameters">
|
||
&reftitle.parameters;
|
||
<para>
|
||
<variablelist>
|
||
<varlistentry>
|
||
<term><parameter>filename</parameter></term>
|
||
<listitem>
|
||
<para>
|
||
Имя читаемого файла.
|
||
</para>
|
||
</listitem>
|
||
</varlistentry>
|
||
<varlistentry>
|
||
<term><parameter>use_include_path</parameter></term>
|
||
<listitem>
|
||
<note>
|
||
<para>
|
||
Можно использовать константу
|
||
<constant>FILE_USE_INCLUDE_PATH</constant> для поиска файла
|
||
в <link linkend="ini.include-path">include path</link>.
|
||
Только помните, что если вы используете <link
|
||
linkend="language.types.declarations.strict">строгую типизацию</link>,
|
||
то так сделать не получится, поскольку
|
||
<constant>FILE_USE_INCLUDE_PATH</constant> имеет тип <type>int</type>.
|
||
В таком случае используйте &true;.
|
||
</para>
|
||
</note>
|
||
</listitem>
|
||
</varlistentry>
|
||
<varlistentry>
|
||
<term><parameter>context</parameter></term>
|
||
<listitem>
|
||
<para>
|
||
Корректный ресурс контекста, созданный с помощью функции
|
||
<function>stream_context_create</function>. Если в использовании
|
||
особого контекста нет необходимости, можно пропустить этот параметр
|
||
передав в него значение &null;.
|
||
</para>
|
||
</listitem>
|
||
</varlistentry>
|
||
<varlistentry>
|
||
<term><parameter>offset</parameter></term>
|
||
<listitem>
|
||
<para>
|
||
Смещение, с которого начнется чтение оригинального потока.
|
||
Отрицательное значение смещения будет отсчитываться с конца потока.
|
||
</para>
|
||
<para>
|
||
Поиск смещения (<parameter>offset</parameter>) не поддерживается при
|
||
работе с удаленными файлами. Попытка поиска смещения на нелокальных
|
||
файлах может работать при небольших смещениях, но результат будет
|
||
непредсказуемым, так как функция работает на буферизованном потоке.
|
||
</para>
|
||
</listitem>
|
||
</varlistentry>
|
||
<varlistentry>
|
||
<term><parameter>maxlen</parameter></term>
|
||
<listitem>
|
||
<para>
|
||
Максимальный размер читаемых данных. По умолчанию чтение
|
||
осуществляется пока не будет достигнут конец файла. Учтите, что
|
||
этот параметр применяется и к потоку с фильтрами.
|
||
</para>
|
||
</listitem>
|
||
</varlistentry>
|
||
</variablelist>
|
||
</para>
|
||
</refsect1>
|
||
|
||
<refsect1 role="returnvalues">
|
||
&reftitle.returnvalues;
|
||
<para>
|
||
Функция возвращает прочтенные данные &return.falseforfailure;.
|
||
</para>
|
||
&return.falseproblem;
|
||
</refsect1>
|
||
|
||
<refsect1 role="errors">
|
||
&reftitle.errors;
|
||
<para>
|
||
Будет сгенерирована ошибка уровня <constant>E_WARNING</constant> в случаях,
|
||
если не удастся найти <parameter>filename</parameter>, задан <parameter>maxlength</parameter>
|
||
меньше нуля, или поиск по смещению <parameter>offset</parameter> в потоке
|
||
завершится неудачно.
|
||
</para>
|
||
</refsect1>
|
||
|
||
<refsect1 role="examples">
|
||
&reftitle.examples;
|
||
<para>
|
||
<example>
|
||
<title>Получить и вывести исходный код домашней страницы сайта</title>
|
||
<programlisting role="php">
|
||
<![CDATA[
|
||
<?php
|
||
$homepage = file_get_contents('http://www.example.com/');
|
||
echo $homepage;
|
||
?>
|
||
]]>
|
||
</programlisting>
|
||
</example>
|
||
<example>
|
||
<title>Поиск файлов в include_path</title>
|
||
<programlisting role="php">
|
||
<![CDATA[
|
||
<?php
|
||
// Если включены строгие типы, то есть объявлено (strict_types=1);
|
||
$file = file_get_contents('./people.txt', true);
|
||
// Иначе
|
||
$file = file_get_contents('./people.txt', FILE_USE_INCLUDE_PATH);
|
||
?>
|
||
]]>
|
||
</programlisting>
|
||
</example>
|
||
<example>
|
||
<title>Чтение секции файла</title>
|
||
<programlisting role="php">
|
||
<![CDATA[
|
||
<?php
|
||
// Читаем 14 символов, начиная с 21 символа
|
||
$section = file_get_contents('./people.txt', FALSE, NULL, 20, 14);
|
||
var_dump($section);
|
||
?>
|
||
]]>
|
||
</programlisting>
|
||
&example.outputs.similar;
|
||
<screen>
|
||
<![CDATA[
|
||
string(14) "lle Bjori Ro"
|
||
]]>
|
||
</screen>
|
||
</example>
|
||
<example>
|
||
<title>Использование потоковых контекстов</title>
|
||
<programlisting role="php">
|
||
<![CDATA[
|
||
<?php
|
||
// Создаем поток
|
||
$opts = array(
|
||
'http'=>array(
|
||
'method'=>"GET",
|
||
'header'=>"Accept-language: en\r\n" .
|
||
"Cookie: foo=bar\r\n"
|
||
)
|
||
);
|
||
|
||
$context = stream_context_create($opts);
|
||
|
||
// Открываем файл с помощью установленных выше HTTP-заголовков
|
||
$file = file_get_contents('http://www.example.com/', false, $context);
|
||
?>
|
||
]]>
|
||
</programlisting>
|
||
</example>
|
||
</para>
|
||
</refsect1>
|
||
|
||
<refsect1 role="changelog">
|
||
&reftitle.changelog;
|
||
<para>
|
||
<informaltable>
|
||
<tgroup cols="2">
|
||
<thead>
|
||
<row>
|
||
<entry>&Version;</entry>
|
||
<entry>&Description;</entry>
|
||
</row>
|
||
</thead>
|
||
<tbody>
|
||
<row>
|
||
<entry>7.1.0</entry>
|
||
<entry>
|
||
Добавлена поддержка отрицательных значений <parameter>offset</parameter>.
|
||
</entry>
|
||
</row>
|
||
</tbody>
|
||
</tgroup>
|
||
</informaltable>
|
||
</para>
|
||
</refsect1>
|
||
|
||
<refsect1 role="notes">
|
||
&reftitle.notes;
|
||
¬e.bin-safe;
|
||
&tip.fopen-wrapper;
|
||
&warn.ssl-non-standard;
|
||
</refsect1>
|
||
|
||
<refsect1 role="seealso">
|
||
&reftitle.seealso;
|
||
<para>
|
||
<simplelist>
|
||
<member><function>file</function></member>
|
||
<member><function>fgets</function></member>
|
||
<member><function>fread</function></member>
|
||
<member><function>readfile</function></member>
|
||
<member><function>file_put_contents</function></member>
|
||
<member><function>stream_get_contents</function></member>
|
||
<member><function>stream_context_create</function></member>
|
||
<member><link linkend="reserved.variables.httpresponseheader">$http_response_header</link></member>
|
||
</simplelist>
|
||
</para>
|
||
</refsect1>
|
||
|
||
</refentry>
|
||
|
||
<!-- Keep this comment at the end of the file
|
||
Local variables:
|
||
mode: sgml
|
||
sgml-omittag:t
|
||
sgml-shorttag:t
|
||
sgml-minimize-attributes:nil
|
||
sgml-always-quote-attributes:t
|
||
sgml-indent-step:1
|
||
sgml-indent-data:t
|
||
indent-tabs-mode:nil
|
||
sgml-parent-document:nil
|
||
sgml-default-dtd-file:"~/.phpdoc/manual.ced"
|
||
sgml-exposed-tags:nil
|
||
sgml-local-catalogs:nil
|
||
sgml-local-ecat-files:nil
|
||
End:
|
||
vim600: syn=xml fen fdm=syntax fdl=2 si
|
||
vim: et tw=78 syn=sgml
|
||
vi: ts=1 sw=1
|
||
-->
|