php包含一个变量然后回显该变量

时间:2016-07-07 15:19:55

标签: php echo php-include

我想将一个文件完全包含在变量中。这样我就可以多次调用这个var并保持代码尽可能干净。但是,当我回显var时,它只返回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

感谢您的帮助!

4 个答案:

答案 0 :(得分:7)

使用file_get_contents代替include()

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

答案 1 :(得分:6)

include不是函数,通常只返回包含操作的状态:

docs

  

处理返回:include失败时返回FALSE并发出警告。 成功包含,除非被包含的文件覆盖,否则返回1 。可以在包含的文件中执行return语句,以终止该文件中的处理并返回调用它的脚本。此外,还可以从包含的文件中返回值。

e.g。

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 ... ?>代码块的情况下执行所包含的代码。否则,任何包含的东西都只被视为输出。

答案 2 :(得分:3)

使用file_get_contentsob_get_clean,如下所示:

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

答案 3 :(得分:2)

以下内容将 include()的返回值指定给变量 $ eyecatcher

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

因为include()成功,它返回一个布尔值 true ,当你回显它时会显示为“1”。

如果您希望将 $ eyecatcher 变量作为字符串加载文件内容,请执行以下操作:

$eyecatcher = file_get_contents($_SERVER['DOCUMENT_ROOT'] . $jpath_eyecatcher_path);
相关问题