如何在变量中执行和获取 .php 文件的内容?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/851367/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to execute and get content of a .php file in a variable?
提问by Prashant
I want to get contents of a .php file in a variable on other page.
我想在其他页面的变量中获取 .php 文件的内容。
I have two files, myfile1.phpand myfile2.php.
我有两个文件,myfile1.php和myfile2.php.
myfile2.php
myfile2.php
<?PHP
$myvar="prashant"; //
echo $myvar;
?>
Now I want to get the value echoed by the myfile2.php in an variable in myfile1.php, I have tried the follwing way, but its taking all the contents including php tag () also.
现在我想在myfile1.php 中的一个变量中得到myfile2.php 回显的值,我尝试了以下方法,但它也获取了包括php 标记() 在内的所有内容。
<?PHP
$root_var .= file_get_contents($_SERVER['DOCUMENT_ROOT']."/myfile2.php", true);
?>
Please tell me how I can get contents returned by one PHP file into a variable defined in another PHP file.
请告诉我如何将一个 PHP 文件返回的内容放入另一个 PHP 文件中定义的变量中。
Thanks
谢谢
采纳答案by zombat
回答by Stefan Gehrig
You have to differentiate two things:
你必须区分两件事:
- Do you want to capture the output (
echo,print,...) of the included file and use the output in a variable (string)? - Do you want to return certain values from the included files and use them as a variable in your hostscript?
- 是否要捕获包含文件的输出 (
echo,print,...) 并在变量(字符串)中使用输出? - 您想从包含的文件中返回某些值并将它们用作主机脚本中的变量吗?
Local variables in your included files will always be moved to the current scope of your hostscript - this should be noted. You can combine all of these features into one:
包含文件中的局部变量将始终移动到主机脚本的当前范围- 应注意这一点。您可以将所有这些功能合二为一:
include.php
include.php
$hello = "Hello";
echo "Hello World";
return "World";
host.php
host.php
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"
The return-feature comes in handy especially when using configuration files.
在return使用配置文件尤其是当-feature就派上用场了。
config.php
config.php
return array(
'host' => 'localhost',
....
);
app.php
app.php
$config = include 'config.php'; // $config is an array
EDIT
编辑
To answer your question about the performance penalty when using the output buffers, I just did some quick testing. 1,000,000 iterations of ob_start()and the corresponding $o = ob_get_clean()take about 7.5 seconds on my Windows machine (arguably not the best environment for PHP). I'd say that the performance impact should be considered quite small...
为了回答您关于使用输出缓冲区时性能损失的问题,我只是做了一些快速测试。在我的 Windows 机器上,1,000,000 次迭代ob_start()和相应的迭代$o = ob_get_clean()大约需要 7.5 秒(可以说不是 PHP 的最佳环境)。我会说性能影响应该被认为非常小......
回答by harto
If you only wanted the content echo()'ed by the included page, you could consider using output buffering:
如果您只想要echo()包含页面的内容,您可以考虑使用输出缓冲:
ob_start();
include 'myfile2.php';
$echoed_content = ob_get_clean(); // gets content, discards buffer
回答by T.Todua
I always try to avoid ob_functions. Instead, I use:
我总是尽量避免使用ob_函数。相反,我使用:
<?php
$file = file_get_contents('/path/to/file.php');
$content = eval("?>$file");
echo $content;
?>
回答by Shanshui
"Actually I was just looking that is there any return type method which can directly give me the value" - You just answered your own question.
“实际上我只是在寻找是否有任何返回类型方法可以直接给我值” - 你刚刚回答了你自己的问题。
See http://sg.php.net/manual/en/function.include.php, Example #5
参见http://sg.php.net/manual/en/function.include.php,示例 #5
file1.php:
文件1.php:
<? return 'somevalue'; ?>
file2.php:
file2.php:
<?
$file1 = include 'file1.php';
echo $file1; // This outputs 'somevalue'.
?>
回答by élektra
You can use output buffers, which will store everything you output, and will not print it out unless you explicitly tell it to, or do not end/clear the buffers by the end of path of execution.
您可以使用输出缓冲区,它将存储您输出的所有内容,除非您明确告诉它,否则不会将其打印出来,或者在执行路径结束时不结束/清除缓冲区。
// Create an output buffer which will take in everything written to
// stdout(i.e. everything you `echo`ed or `print`ed)
ob_start()
// Go to the file
require_once 'file.php';
// Get what was in the file
$output = ob_get_clean();
回答by Jeff Williams
If you want to return the output from code in a file, simply just make a RESTful API call to it. This way, you can use the same code file for ajax calls, REST API, or for your internal PHP code.
如果您想从文件中的代码返回输出,只需对其进行 RESTful API 调用即可。这样,您可以将相同的代码文件用于 ajax 调用、REST API 或您的内部 PHP 代码。
It requires cURL to be installed but no output buffers or no includes, just the page executed and returned into a string.
它需要安装 cURL 但没有输出缓冲区或没有包含,只需要执行页面并返回一个字符串。
I'll give you the code I wrote. It works with nearly every REST/web server (and even works with Equifax):
我给你我写的代码。它几乎适用于所有 REST/Web 服务器(甚至适用于 Equifax):
$return = PostRestApi($url);
or
或者
$post = array('name' => 'Bob', 'id' => '12345');
$return = PostRestApi($url, $post, false, 6, false);
Here is the function:
这是函数:
/**
* Calls a REST API and returns the result
*
* $loginRequest = json_encode(array("Code" => "somecode", "SecretKey" => "somekey"));
* $result = CallRestApi("https://server.com/api/login", $loginRequest);
*
* @param string $url The URL for the request
* @param array/string $data Input data to send to server; If array, use key/value pairs and if string use urlencode() for text values)
* @param array $header_array Simple array of strings (i.e. array('Content-Type: application/json');
* @param int $ssl_type Set preferred TLS/SSL version; Default is TLSv1.2
* @param boolean $verify_ssl Whether to verify the SSL certificate or not
* @param boolean $timeout_seconds Timeout in seconds; if zero then never time out
* @return string Returned results
*/
function PostRestApi($url, $data = false, $header_array = false,
$ssl_type = 6, $verify_ssl = true, $timeout_seconds = false) {
// If cURL is not installed...
if (! function_exists('curl_init')) {
// Log and show the error
$error = 'Function ' . __FUNCTION__ . ' Error: cURL is not installed.';
error_log($error, 0);
die($error);
} else {
// Initialize the cURL session
$curl = curl_init($url);
// Set the POST data
$send = '';
if ($data !== false) {
if (is_array($data)) {
$send = http_build_query($data);
} else {
$send = $data;
}
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($curl, CURLOPT_POSTFIELDS, $send);
}
// Set the default header information
$header = array('Content-Length: ' . strlen($send));
if (is_array($header_array) && count($header_array) > 0) {
$header = array_merge($header, $header_array);
}
curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
// Set preferred TLS/SSL version
curl_setopt($curl, CURLOPT_SSLVERSION, $ssl_type);
// Verify the server's security certificate?
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, ($verify_ssl) ? 1 : 0);
// Set the time out in seconds
curl_setopt($curl, CURLOPT_TIMEOUT, ($timeout_seconds) ? $timeout_seconds : 0);
// Should cURL return or print out the data? (true = return, false = print)
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
// Execute the request
$result = curl_exec($curl);
// Close cURL resource, and free up system resources
curl_close($curl);
unset($curl);
// Return the results
return $result;
}
}
回答by vish
If you want to get all over site use by
如果你想得到整个网站的使用
<?php
$URL = 'http://www.example.com/';
$homepage = file_get_contents($URL);
echo $homepage;
?>
回答by Chinmay235
Please try this code
请试试这个代码
myfile1.php
我的文件1.php
<?php
echo file_get_contents("http://domainname/myfile2.php");
?>
myfile2.php
myfile2.php
<?PHP
$myvar="prashant";
echo $myvar;
?>

