Help with including HTML from an external file into my php file

Hi,

I’m working on starting to clean up some of the php code I’m doing, and split out some of the HTML it uses.

I have a function that writes a bunch of HTML into a string, and then returns the string. It’s basically this:

[php]function create_content() {
$output = ‘’;
$output .= ’


some text




some other text



</article>
';
return $output;

}

[/php]It works like I want it to.

I was thinking I’d move the HTML code into a file.

So I created a file, “my_file.inc” which has in it:

[code]

some text




some other text



</article>

[/code]
And changed the funtion to instead include it

[php]function create_content() {
$output = ‘’;
$output .= include("./my_file.inc");
return $output;
}
[/php]

With the ‘include’, it finds the file, but the display of the content gets moved from where it it in the original way, and gets put above everything on my page.

I also tried ‘require’, ‘readfile’, and a bunch of other php commands instead of include.

I sometimes get the display but in the wrong place. Other times, I get no display at all. Sometimes I just see a “1” displayed.

But I never get the display from the file in the right place :-/

I think it has to do with wrong use of quotes, or something. I’ve been running around in circles on this for a couple of days. In the IRC they told me the stuff I tried above. Nothing helps.

I figured I needed to ask for some help here.

Anybody?

Thanks a lot!!

Include sends a HTTP header outbound which is causing your problem which you can control using output buffering : ob_start();

PHP.net has a great example of the EXACT same thing your trying to do.

Example #6 Using output buffering to include a PHP file into a string

[php]$string = get_include_contents(‘somefile.php’);

function get_include_contents($filename) {
if (is_file($filename)) {
ob_start();
include $filename;
return ob_get_clean();
}
return false;
}[/php]

http://php.net/manual/en/function.include.php

Hey that worked! That’s great, thanks :smiley:

I didn’t understand the ob_start() business but your pointing me at the example has got me started on that too!

One thing I noticed using it this way is that it takes ~ a full second longer to load the “included” HTML into my page than if I hardwire it right into the php function like I originally had.

I guess the includ-ing process and the ob_start() procedure take some time to execute.

Is this probably it? Is ~ 1 sec about what you’d expect?

Yes, output buffering is basically “building” the page in a buffer before it’s sent back to the client so additional headers throughout the script don’t break the output. There will be a delay. There’s ways to do it without output buffering as well - it was just the simplest solution I think in this case. Another thing you can look at is view/template managers such as Smarty Templates.

Sponsor our Newsletter | Privacy Policy | Terms of Service