如何在heredoc变量中插入php include?

7

我需要在php heredoc变量中包含页面,但它不起作用,请帮助我。

$content = <<<EOF
include 'links.php';
EOF;
5个回答

19

你可以这样做:

ob_start();
include 'links.php';
$include = ob_get_contents();
ob_end_clean();

$content = <<<EOF
{$include}
EOF;

3
你可以将 ob_get_contentsob_end_clean 结合使用,来达到 ob_get_clean 的效果 :) - NikiC

3

简单来说,你不能直接做到这一点。你可以预先包含文件,将其存储在变量中,然后将其插入文件中。例如:

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

5
这将包括links.php的源代码,而不包括执行后的内容。 - Rudu
不要在运行file_get_contents之后使用eval。它不会按照你的期望工作。原因是include(因此是links.php文件)从关闭PHP解释器的状态开始。这就是为什么你需要<?php来打开它(它开始于非代码上下文)。eval从打开解释器的状态开始(你不需要在php代码前加上<?php来使其工作)。所以它不会按照你的期望工作。更不用说eval的其他弊端了...所以,这归结为错误建议,不会起作用,扣1分。 - ircmaxell

2
你所说的“不工作”是指'links.php'的内容没有在$content中吗?如果是这样,你可以尝试使用输出流重定向(或只需读取文件)。以下是示例代码:
<?php
ob_start();
include 'links.php';
$content = ob_get_contents();
ob_end_clean();
echo "contents=[$content]\n"; ?>

1
叹气 每次我回答一个没有答案的问题,我还没打完,就会有3或4个答案。 - troutinator

1

完全不要使用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*/?>

1

Heredoc 语法只用于处理纯文本。您无法在其中包含文件或执行 PHP 方法。


资源:


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接