使用 include() 设置$variable的内容


Setting $variable's content using include()

我正在尝试通过 PHP 的 email(( 函数发送凭证,其中我使用 include(( 作为消息内容引用外部.php文件。这是代码:

$message = '<?php include ("/fullpath/inc/voucher.php"); ?>';

这是行不通的,因为我将其声明为文本字符串,但是如果我不这样做,它只会打印出内容,而不是将其作为变量的内容。有什么想法吗?

您可以使用ob_buffer,请尝试以下操作:

<?php
   ob_start();  // start buffer
   include("file.php");  // read in buffer
   $var=ob_get_contents();  // get buffer content
   ob_end_clean();  // delete buffer content
   echo $var;  // use $var
?>

http://www.webmaster-eye.de/include-in-Variable-umleiten.210.artikel.html 示例(德语(

在这篇文章中,将根据情况描述两种解决方案。

<小时 />

voucher.php返回一个值

如果 voucher.php 中有 return 语句,则可以安全地使用 include 来获取此返回值。

请参阅以下示例:

凭证.php

<?php
$contents = "hello world!";
...
return $contents;
?>

$message = include ("/fullpath/inc/voucher.php");
<小时 />

voucher.php打印我想存储在变量中的数据

如果voucher.php打印要存储在变量中的数据,则可以使用 php 的输出缓冲函数存储打印的数据,然后将其分配给$message

ob_start ();
  include ("/fullpath/inc/voucher.php");
  $message = ob_get_contents ();
ob_end   ();
ob_start();
include ("/fullpath/inc/voucher.php");
$message = ob_get_clean();

但是,在大多数情况下,输出缓冲被认为是不好的做法,不建议使用

就像在你的情况下,你最好在 voucher.php 中声明一个函数,该函数将消息作为字符串返回。所以所有代码都可以像这样简单:$message = get_voucher();

我遇到了同样的问题,这是为我解决问题的函数。它使用托比斯克答案

function call_plugin($target_) { // $target_ is the path to the .PHP file
        ob_start();  // start buffer
        include($target_);  // read in buffer
        $get_content = ob_get_contents();  // get buffer content
        ob_end_clean();
        return $get_content;
    }
您希望

使用 readfile() 函数而不是包含。请参阅:http://en.php.net/manual/en/function.readfile.php

如果你想得到 PHP 解析凭证的 =results=.php一种方法是确保将凭证.php放在可访问的 URL 上,然后像这样调用它:

$message = file_get_contents("http://host.domain.com/blabla/voucher.php");

这会将解析的凭证的内容/输出.php插入到变量$message中。

如果你无法访问凭证.php公开地你必须重写它以最终使用 return(( 函数输出字符串,或者在凭证中编写一个函数.php在调用时输出你想要的字符串,之后你包含(( 它并从这个主 PHP 脚本中调用该函数。

$message = include '/fullpath/inc/voucher.php';

/fullpath/inc/voucher.php

// create $string;
return $string;
$message=file_get_contents("/fullpath/inc/voucher.php");