php 包含到变量中然后回显该变量

php include into a variable then echo that variable

我想将一个文件完全包含到一个变量中。这样我就可以多次调用这个 var 并尽可能保持代码干净。但是当我回显 var 时它只 returns a 1 并且当我对它自己使用 include 时它输出整个文件。

我想输出包含的文件和运行里面的所有php代码。

所以我做错了什么。

default.php

$jpath_eyecatcher = (JURI::base(). "modules/mod_eyecatcher/tmpl/content/eyecatcher.php");
$jpath_eyecatcher_path = parse_url($jpath_eyecatcher, PHP_URL_PATH);
ob_start();
$eyecatcher = include ($_SERVER['DOCUMENT_ROOT'] . $jpath_eyecatcher_path);
ob_end_clean();


echo $eyecatcher . '<br>';

include ($_SERVER['DOCUMENT_ROOT'] . $jpath_eyecatcher_path);

echo 输出是

1

包括输出是

eyecatchertype = 2 
fontawesome
envelope-o
insert_emoticon
custom-icon-class
128
images/clientimages/research (1).jpg
top
test

感谢您的帮助!

使用file_get_contents代替include()

include() 执行文件中给定的 php 代码,而 file_get_contents() 为您提供文件内容。

使用file_get_contentsob_get_clean,像这样:

ob_start();
include ($_SERVER['DOCUMENT_ROOT'] . $jpath_eyecatcher_path);
$eyecatcher = ob_get_clean();

include不是函数,一般只有returns包含操作的状态:

docs:

Handling Returns: include returns FALSE on failure and raises a warning. Successful includes, unless overridden by the included file, return 1. It is possible to execute a return statement inside an included file in order to terminate processing in that file and return to the script which called it. Also, it's possible to return values from included files.

例如

x.php:

<?php
return 42;

y.php

<?php
$y = 'foo';

z.php

<?php
$z = include 'x.php';
echo $z; // outputs 42

$y = include 'y.php';
echo $y; // ouputs 1, for 'true', because the include was successful
         // and the included file did not have a 'return' statement.

另请注意,include 只有包含 <?php ... ?> 代码块时才会执行包含的代码。否则,包含的任何内容都将被简单地视为输出。

下面将include()的return值赋值给变量$eyecatcher.

$eyecatcher = include ($_SERVER['DOCUMENT_ROOT'] . $jpath_eyecatcher_path);

因为 include() 成功,它 return 是一个 true 的布尔值,回显时显示为“1”。

如果您希望将文件内容作为字符串加载 $eyecatcher 变量,您可以这样做:

$eyecatcher = file_get_contents($_SERVER['DOCUMENT_ROOT'] . $jpath_eyecatcher_path);