如何在变量中执行和获取.php文件的内容?

Pra*_*ant 18 php return file file-get-contents

我想在其他页面上的变量中获取.php文件的内容.

我有两个文件,myfile1.phpmyfile2.php.

myfile2.php

<?PHP
    $myvar="prashant"; // 
    echo $myvar;
?>
Run Code Online (Sandbox Code Playgroud)

现在我想在myfile1.php中的变量中获取myfile2.php回显的值,我尝试了以下方式,但它也采用了包括php tag()在内的所有内容.

<?PHP
    $root_var .= file_get_contents($_SERVER['DOCUMENT_ROOT']."/myfile2.php", true);
?>
Run Code Online (Sandbox Code Playgroud)

请告诉我如何将一个PHP文件返回的内容转换为另一个PHP文件中定义的变量.

谢谢

Ste*_*rig 32

你必须区分两件事:

  • 是否要捕获包含文件的输出(echo,, print...)并在变量(字符串)中使用输出?
  • 是否要从包含的文件中返回某些值并将其用作主机脚本中的变量?

所包含文件中的局部变量将始终移动到主机脚本的当前范围- 这应该注意.您可以将所有这些功能合并为一个:

include.php

$hello = "Hello";
echo "Hello World";
return "World";
Run Code Online (Sandbox Code Playgroud)

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"
Run Code Online (Sandbox Code Playgroud)

return使用配置文件尤其是当-feature就派上用场了.

config.php

return array(
    'host' => 'localhost',
     ....
);
Run Code Online (Sandbox Code Playgroud)

app.php

$config = include 'config.php'; // $config is an array
Run Code Online (Sandbox Code Playgroud)

编辑

要回答关于使用输出缓冲区时性能损失的问题,我只是做了一些快速测试.在我的Windows机器上进行了1,000,000次迭代,ob_start()相应的$o = ob_get_clean()约需7.5秒(可能不是PHP的最佳环境).我会说性能影响应该被认为很小......


har*_*rto 18

如果您只想要echo()包含页面的内容,您可以考虑使用输出缓冲:

ob_start();
include 'myfile2.php';
$echoed_content = ob_get_clean(); // gets content, discards buffer
Run Code Online (Sandbox Code Playgroud)

http://php.net/ob_start


T.T*_*dua 11

我总是试图避免ob_功能.相反,我使用:

<?php
$file = file_get_contents('/path/to/file.php');
$content = eval("?>$file");
echo $content;
?>
Run Code Online (Sandbox Code Playgroud)

  • 如果 eval() 是答案,那么您几乎肯定问错了问题。-- Rasmus Lerdorf,PHP 的 BDFL (4认同)
  • 你的回答很有趣.你可以分享为什么你要避免输出缓冲,并使用eval()代替?你的答案对我来说是一个很好的知识. (2认同)

zom*_*bat 5

您可以使用include指令来执行此操作。

文件2:

<?php
    $myvar="prashant";
?>
Run Code Online (Sandbox Code Playgroud)

文件 1:

<?php 

include('myfile2.php');
echo $myvar;

?>
Run Code Online (Sandbox Code Playgroud)


Sha*_*hui 5

"实际上我只是在寻找那种可以直接给我价值的返回类型方法" - 你刚回答了自己的问题.

请参见http://sg.php.net/manual/en/function.include.php,示例#5

file1.php:

<? return 'somevalue'; ?>
Run Code Online (Sandbox Code Playgroud)

file2.php:

<?

$file1 = include 'file1.php';
echo $file1; // This outputs 'somevalue'.

?>
Run Code Online (Sandbox Code Playgroud)


Éle*_*tra 5

您可以使用输出缓冲区,它将存储您输出的所有内容,并且不会打印出来,除非您明确告诉它,或者在执行路径结束时不要结束/清除缓冲区。

// 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();
Run Code Online (Sandbox Code Playgroud)