我需要在php heredoc变量中包含页面,但它不起作用,请帮助我。
$content = <<<EOF
include 'links.php';
EOF;
我需要在php heredoc变量中包含页面,但它不起作用,请帮助我。
$content = <<<EOF
include 'links.php';
EOF;
你可以这样做:
ob_start();
include 'links.php';
$include = ob_get_contents();
ob_end_clean();
$content = <<<EOF
{$include}
EOF;
简单来说,你不能直接做到这一点。你可以预先包含文件,将其存储在变量中,然后将其插入文件中。例如:
$links_contents = file_get_contents('links.php');
//$links_contents = eval($links_contents); // if you need to execute PHP inside of the file
$content = <<<EOF
{$links_contents}
EOF;
links.php
的源代码,而不包括执行后的内容。 - Rudufile_get_contents
之后使用eval
。它不会按照你的期望工作。原因是include
(因此是links.php
文件)从关闭PHP解释器的状态开始。这就是为什么你需要<?php
来打开它(它开始于非代码上下文)。eval
从打开解释器的状态开始(你不需要在php代码前加上<?php
来使其工作)。所以它不会按照你的期望工作。更不用说eval
的其他弊端了...所以,这归结为错误建议,不会起作用,扣1分。 - ircmaxell<?php ob_start(); include 'links.php'; $content = ob_get_contents(); ob_end_clean();
echo "contents=[$content]\n"; ?>
完全不要使用heredoc。
如果需要输出内容 - 只需将其原样输出,无需将其存储在变量中。
可以非常有限地使用输出缓冲区,但我确定这里没有这种情况。
只需准备好数据,然后使用纯HTML和PHP输出它。
像这样制作您的页面(直接从其他最近的答案中):
news.php:
<?
include "config.php"; //connect to database HERE.
$data = getdbdata("SELECT * FROM news where id = %d",$_GET['id']);
$page_title = $data['title'];
$body = nl2br($data['body']);
$tpl_file = "tpl.news.php";
include "template.php";
?>
template.php:
<html>
<head>
<title><?=$page_title?></title>
</head>
<body>
<? include $tpl_file?>
</body>
tpl.news.php
<h1><?=$page_title?></h1>
<?=$body?>
<? include "links.php" /*include your links anywhere you wish*/?>
ob_get_contents
和ob_end_clean
结合使用,来达到ob_get_clean
的效果 :) - NikiC