0

I have this:

  ob_start();                     ?>
          <div class="" id="loading">
               <?php echo file_get_contents($page["texto"]) ?> 
          </div>      <?php

  $content = ob_get_clean();

But I would like to have that template html in a separate file, just like:

$content = file_get_contents('cms/template.php');

Now this won't work because it has php tags inside and when retrieving the string it gets as

how can I achieve this without using a dirty hack like:

$pre = file_get_contents('part1');
$var = file_get_contents($page["texto"]);
$post = file_get_contents('part2');

And adding all them...

1 Answer 1

3

It's still hack, but unless you use a templating system like Twig you have no choice:

ob_start();
include 'cms/template.php';
$content = ob_get_clean();

echo $content;

ob_start enables output buffering so nothing gets sent to the browser. We then include the file which will execute PHP normally. We then use ob_get_clean to get the contents of the output buffer (which is your template file). and disable the output buffer, discarding it's contents, as we have the contents in $content.

Sign up to request clarification or add additional context in comments.

4 Comments

That was so stupidly easy... It worked fine! I couldn't figure that mixing include and ob_ would work like that... I'm accepting your anwser in 7 mins
I don't consider that a hack. You're taking advantage of PHP's features. You have some text that needs to be processed and stored, but not displayed. The ob_* set of functions is perfect for that.
@TecBrat I know, it's pretty much the best solution we have. I just wish PHP had a function like include/require that returned output as a variable so we didn't have to do this.
Still much better than making it in three files. tyvm

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.