Php содержимое файла присвоить переменной

Как выполнить и получить содержимое файла .php в переменную?

Теперь я хочу получить значение, выраженное myfile2.php в переменной в myfile1.php, я пробовал этот способ, но он также принимает все содержимое, включая php tag().

Расскажите, как я могу получить содержимое, возвращенное одним файлом PHP, в переменную, определенную в другом файле PHP. Спасибо

ВСЕГДА ob_get_contents() , потому что если вы будете использовать ob_get_contents() , то вам может понадобиться сделать ob_end_flush , в противном случае у вас могут возникнуть проблемы, если вы будете использовать любую команду header php после этого.

8 ответов

Для этого вы можете использовать директиву include.

На самом деле я просто искал, есть ли какой-нибудь метод типа «возврат», который может дать мне значение. В любом случае я принял ответ @ zombat, так как метод, предложенный @harto, может иметь некоторые проблемы с производительностью, и я не могу пойти на компромисс с производительностью. Спасибо, парень.

Вы должны различать две вещи:

  • Вы хотите захватить вывод ( echo , print . ) включенного файла и использовать вывод в переменной (строке)?
  • Вы хотите вернуть определенные значения из включенных файлов и использовать их в качестве переменной в своем хосте script?

Локальные переменные в ваших включенных файлах всегда будут перемещены в текущую область вашего хоста script — это следует отметить. Вы можете объединить все эти функции в один:

$hello = "Hello"; echo "Hello World"; return "World"; 
ob_start(); $return = include 'include.php'; // (string)"World" $output = ob_get_clean(); // (string)"Hello World" // $hello has been moved to the current scope echo $hello . ' ' . $return; // echos "Hello World" 

return -feature пригодится, особенно при использовании файлов конфигурации.

return array( 'host' => 'localhost', . ); 
$config = include 'config.php'; // $config is an array 

Чтобы ответить на вопрос о снижении производительности при использовании выходных буферов, я просто немного быстро проверил. 1,000,000 итераций ob_start() , а соответствующий $o = ob_get_clean() занимает около 7,5 секунд на моей машине Windows (возможно, это не лучшая среда для PHP). Я бы сказал, что влияние производительности должно считаться довольно маленьким.

Источник

file_get_contents

This function is similar to file() , except that file_get_contents() returns the file in a string , starting at the specified offset up to length bytes. On failure, file_get_contents() will return false .

file_get_contents() is the preferred way to read the contents of a file into a string. It will use memory mapping techniques if supported by your OS to enhance performance.

Note:

If you’re opening a URI with special characters, such as spaces, you need to encode the URI with urlencode() .

Parameters

Note:

The FILE_USE_INCLUDE_PATH constant can be used to trigger include path search. This is not possible if strict typing is enabled, since FILE_USE_INCLUDE_PATH is an int . Use true instead.

A valid context resource created with stream_context_create() . If you don’t need to use a custom context, you can skip this parameter by null .

The offset where the reading starts on the original stream. Negative offsets count from the end of the stream.

Seeking ( offset ) is not supported with remote files. Attempting to seek on non-local files may work with small offsets, but this is unpredictable because it works on the buffered stream.

Maximum length of data read. The default is to read until end of file is reached. Note that this parameter is applied to the stream processed by the filters.

Return Values

The function returns the read data or false on failure.

This function may return Boolean false , but may also return a non-Boolean value which evaluates to false . Please read the section on Booleans for more information. Use the === operator for testing the return value of this function.

Errors/Exceptions

An E_WARNING level error is generated if filename cannot be found, length is less than zero, or if seeking to the specified offset in the stream fails.

When file_get_contents() is called on a directory, an E_WARNING level error is generated on Windows, and as of PHP 7.4 on other operating systems as well.

Changelog

Version Description
8.0.0 length is nullable now.
7.1.0 Support for negative offset s has been added.

Examples

Example #1 Get and output the source of the homepage of a website

Example #2 Searching within the include_path

// If strict types are enabled i.e. declare(strict_types=1);
$file = file_get_contents ( ‘./people.txt’ , true );
// Otherwise
$file = file_get_contents ( ‘./people.txt’ , FILE_USE_INCLUDE_PATH );
?>

Example #3 Reading a section of a file

// Read 14 characters starting from the 21st character
$section = file_get_contents ( ‘./people.txt’ , FALSE , NULL , 20 , 14 );
var_dump ( $section );
?>

The above example will output something similar to:

Example #4 Using stream contexts

// 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 );
?>

Notes

Note: This function is binary-safe.

A URL can be used as a filename with this function if the fopen wrappers have been enabled. See fopen() for more details on how to specify the filename. See the Supported Protocols and Wrappers for links to information about what abilities the various wrappers have, notes on their usage, and information on any predefined variables they may provide.

When using SSL, Microsoft IIS will violate the protocol by closing the connection without sending a close_notify indicator. PHP will report this as «SSL: Fatal Protocol Error» when you reach the end of the data. To work around this, the value of error_reporting should be lowered to a level that does not include warnings. PHP can detect buggy IIS server software when you open the stream using the https:// wrapper and will suppress the warning. When using fsockopen() to create an ssl:// socket, the developer is responsible for detecting and suppressing this warning.

See Also

  • file() — Reads entire file into an array
  • fgets() — Gets line from file pointer
  • fread() — Binary-safe file read
  • readfile() — Outputs a file
  • file_put_contents() — Write data to a file
  • stream_get_contents() — Reads remainder of a stream into a string
  • stream_context_create() — Creates a stream context
  • $http_response_header

User Contributed Notes 6 notes

file_get_contents can do a POST, create a context for that first:

$opts = array( ‘http’ =>
array(
‘method’ => ‘POST’ ,
‘header’ => «Content-Type: text/xml\r\n» .
«Authorization: Basic » . base64_encode ( » $https_user : $https_password » ). «\r\n» ,
‘content’ => $body ,
‘timeout’ => 60
)
);

$context = stream_context_create ( $opts );
$url = ‘https://’ . $https_server ;
$result = file_get_contents ( $url , false , $context , — 1 , 40000 );

Note that if an HTTP request fails but still has a response body, the result is still false, Not the response body which may have more details on why the request failed.

There’s barely a mention on this page but the $http_response_header will be populated with the HTTP headers if your file was a link. For example if you’re expecting an image you can do this:

$mimetype = null ;
foreach ( $http_response_header as $v ) if ( preg_match ( ‘/^content\-type:\s*(image\/[^;\s\n\r]+)/i’ , $v , $m )) $mimetype = $m [ 1 ];
>
>

if (! $mimetype ) // not an image
>

if the connection is
content-encoding: gzip
and you need to manually ungzip it, this is apparently the key
$c=gzinflate( substr($c,10,-8) );
(stolen from the net)

//从指定位置获取指定长度的文件内容
function file_start_length($path,$start=0,$length=null) if(!file_exists($path)) return false;
$size=filesize($path);
if($start <0) $start+=$size;
if($length===null) $length=$size-$start;
return file_get_contents($path, false, null, $start, $length );
>

I’m not sure why @jlh was downvoted, but I verified what he reported.

>>> file_get_contents($path false, null, 5, null)
=> «»
>>> file_get_contents($path, false, null, 5, 5)
=> «r/bin»

Источник

Как присвоить переменной значения из текстового файла?

Подскажите пожалуйста, как мне присвоить переменной $to значения из какого-либо текстовика, в котором будет список телефонов(mysql не подходит) чтобы скрипт выполнялся для каждого значения?

Как присвоить переменной содержимое текстового файла?
На Batch ИМХО невозможно. Нет способа обращаться к строчке. PS Предлагаю разместить код.

Как присвоить переменной содержимое строки из текстового файла?
Например, есть файл 1.txt в нем только одна строка "123" как её присвоить переменной "a".

Как присвоить переменной значение в виде определённых концевых частей строк из текстового файла?
есть допустим строки в текстовом файле: -rw-r—r— 1474560 2013/08/23 01:20:53 VM-test.vfd.

Присвоить переменным значения из текстового файла
Здравствуйте. Только начинаю познавать великий и прекрасный Си "сложить" "сложить", просьба не.

Лучший ответ

Сообщение было отмечено StillFree как решение

Решение

Вы хотите построчно вставлять данные из текстового файла в переменную $to?

Добавлено через 19 минут

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
function selectPhone () { $handle = fopen('nomera.txt', 'rb') or die("Ошибка открытия файла!"); while (!feof($handle)) { $nomer = fgets($handle); $to = $nomer; $from = smsc; $coding = 2; $txt = "бла-бла-бла"; $text = urlencode(iconv("utf-8","ucs-2be",$txt)); $url = "http://172.27.27.53:11003/cgi-bin/sendsms?user=123&password=456&from=$from&to=$to&text=$text&coding=$coding"; file_get_contents($url); } fclose($handle); } selectPhone();

Источник

Как назначить содержимое файла переменной в PHP

У меня есть файл документа, содержащий разметку HTML. Я хочу назначить содержимое всего файла переменной PHP.

У меня есть эта строка кода:

Когда я делаю var_dump() я получаю string(1) «‘»

Можно ли присвоить содержимое файла переменной?

[Примечание: причина для этого заключается в том, что я хочу отделить сегмент тела почтового сообщения от сценария почтовой программы – вроде как шаблон, так что пользователь просто модифицирует разметку HTML и не должен заботиться о моем почтовом ящике скрипт. Поэтому я включаю файл как весь сегмент тела по mail($to, $subject, $body, $headers, $return_path);

Solutions Collecting From Web of «Как назначить содержимое файла переменной в PHP»

Если есть PHP-код, который нужно выполнить, вам действительно нужно использовать include . Однако include не будет возвращать выходные данные из файла; он будет отправлен в браузер. Вам нужно использовать функцию PHP, называемую выходной буферизацией: это фиксирует все выходные данные, отправленные скриптом. Затем вы можете получить доступ к этим данным и использовать их:

ob_start(); // start capturing output include('email_template.php'); // execute the file $content = ob_get_contents(); // get the contents from the buffer ob_end_clean(); // stop buffering and discard contents в ob_start(); // start capturing output include('email_template.php'); // execute the file $content = ob_get_contents(); // get the contents from the buffer ob_end_clean(); // stop buffering and discard contents 

Вы должны использовать file_get_contents() :

$body1 = file_get_contents('email_template.php'); 

include включает и выполняет email_template.php в вашем текущем файле и сохраняет возвращаемое значение include() в $body1 .

Если вам нужно выполнить PHP-код внутри файла, вы можете использовать управление выходом :

ob_start(); include 'email_template.php'; $body1 = ob_get_clean(); 
$file = file_get_contents('email_template.php'); 
ob_start(); include('email_template.php'); $file = ob_end_flush(); в ob_start(); include('email_template.php'); $file = ob_end_flush(); 

Как и другие публикации, используйте file_get_contents если этот файл не нужно выполнять каким-либо образом.

В качестве альтернативы вы можете включить включение возвращаемого результата с помощью оператора return.

Если вы включили обработку и выходы с помощью команд echo [ed: or leave PHP parsing mode], вы также можете буферизовать вывод.

ob_start(); include('email_template.php'); $body1 = ob_get_clean(); в ob_start(); include('email_template.php'); $body1 = ob_get_clean(); 

Попробуйте использовать функцию file_get_contents() PHP.

В файле, который вы хотите использовать переменную, поместите это

require_once '/myfile.php'; if(isset($responseBody)) с require_once '/myfile.php'; if(isset($responseBody))

В файле, который вы вызываете /myfile.php, поместите это

$responseBody = 'Hello world, I am a genius'; 

Источник

Читайте также:  Example for java inheritance
Оцените статью