繁体   English   中英

PHP包含到一个变量,然后回显该变量

[英]php include into a variable then echo that variable

我想将文件完全包含到变量中。 这样我可以多次调用此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);

回显输出为

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()提供文件内容。

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

docs

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

例如

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 ... ?>代码块的情况下才执行包含的代码。 否则,包含的所有内容都将被简单地视为输出。

使用file_get_contentsob_get_clean ,如下所示:

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

以下代码将include()的返回值分配给变量$ eyecatcher

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

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM