Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP include inside of a variable

I have a function that is controlling the output of my page:

$page = "<div class='media-title'><h2>{$title}</h2></div><div class='media-image'>{$image}</div><div class='media-desc'>{$desc}</div>";

I would like to include a file "box.php" inside that html that is defined in the $page variable. I tried this:

$page = "<div class='media-title'><h2>{$title}</h2></div><div class='media-image'>{$image}</div><div class="inlinebox">" . include("box.php"); . "</div><div class='media-desc'>{$desc}</div>";

... but it didn't work. How can I put a php include inside of a variable?

like image 674
mattz Avatar asked Dec 09 '10 23:12

mattz


2 Answers

from php.net

// put this somewhere in your main file, outside the
// current function that contains $page
function get_include_contents($filename) {
    if (is_file($filename)) {
        ob_start();
        include $filename;
        $contents = ob_get_contents();
        ob_end_clean();
        return $contents;
    }
    return false;
}

// put this inside your current function
$string = get_include_contents('box.php');
$page  = '<div class="media-title"><h2>{$title}</h2></div>';
$page .= '<div class="media-image">{$image}</div>';
$page .= '<div class="inlinebox">' . $string . '</div>';
$page .= '<div class="media-desc">{$desc}</div>';
like image 174
Stephen Avatar answered Sep 17 '22 09:09

Stephen


How can I put a php include inside of a variable?

# hello.php
<?php
  return "Hello, World!";
?>

# file.php
$var = include('hello.php');
echo $var;

I would generally avoid such a thing though.

like image 30
Matthew Avatar answered Sep 21 '22 09:09

Matthew