Hello everyone,

I would like to include HTML from an external file, store it in a variable and then echo it, like so:

$html = include("stuff.html");
 echo "$html";

Everything in the code is working ok, except for the fact that I get a 1 echoed back after the html file.

Any ideas please?

Thanks

If you have php version 5 then use the following:

$html = file_get_contents("stuff.html");
echo $html;

include doesn't return the contents of a file.

you would need to do a ob_start(), then include, then ob_get_contents() to get the file contents from an include.

i would use file_get_contents();

include doesn't return the contents of a file.

you would need to do a ob_start(), then include, then ob_get_contents() to get the file contents from an include.

i would use file_get_contents();

That is technically incorrect. Include can retieve the contents of a php file if the php file is designed to submit the contents. Below is an example to prove that.

<?
//index.php
$var=include('myfile.php');
echo "<hr>";
echo $var;
echo "<hr>";
echo $myvar;
?>
<?
//myfile.php
$output="<html>";
$output.="<body bgcolor=#00FFFF>";
$output.="This is the body";
$myvar='This is a test';
$output.="</body>";
$output.="</html>";
//submit output.
return $output;
?>

As you can see, in my example you can include a php file and return the execution of php code. Really simple but you must return the contents as displayed html will not be passed on. This means for my above example to work, you cannot use the echo or print function within the myfile.php and all the code in the php file need to be pure php (in myfile.php). Just a note to keep in mind.

commented: Great explanation with example :) +3
commented: Good Analyising about include function.. +2

Ok thanks, that has solved my problem.

Member Avatar for diafol

Why do you want to store it in a variable? why not just include the file?

include('/abspath/file');
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.