简体   繁体   中英

php include into a variable then echo that variable

I want to include a file entirely into a variable. So that I can call this var multiple times and keep the code as clean as possible. But when I echo the var it only returns a 1 and when I use the include on itself it output the entire file.

I want to output the included file and run all php code inside it.

So what am I doing wrong here.

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 output is

1

include output is

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

Thanks for the help!

Use file_get_contents instead of include()

include() executes the php code given in the file, whereas file_get_contents() gives you the file content.

include is not a function, and normally only returns the status of the include operation:

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.

eg

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.

Also note that include will only execute the included code if it contains <?php ... ?> code block. Otherwise anything included is simply treated as output.

Use file_get_contents or ob_get_clean , like so:

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

The following assigns the return value of include() to the variable $eyecatcher .

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

Because the include() was successful, it returns a boolean value of true , which is presented as "1" when you echo it.

If you wish to load the $eyecatcher variable with the contents of the file as a string, you do:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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