PHP包含变量内部

mat*_*ttz 6 php variables function include

我有一个控制页面输出的函数:

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

我想在$page变量中定义的html中包含一个文件"box.php" .我试过这个:

$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>";

......但它没有用.我怎样才能在变量中加入一个php include?

Ste*_*hen 13

来自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>';
Run Code Online (Sandbox Code Playgroud)


Mat*_*hew 9

我怎样才能在变量中加入一个php include?

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

# file.php
$var = include('hello.php');
echo $var;
Run Code Online (Sandbox Code Playgroud)

我通常会避免这样的事情.