如何插入php包含heredoc变量?
我需要包含页面里面的PHP heredoc变量,但它不起作用,请帮助我。如何插入php包含heredoc变量?
$content = <<<EOF
include 'links.php';
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;
你可以这样说:
ob_start();
include 'links.php';
$include = ob_get_contents();
ob_end_clean();
$content = <<<EOF
{$include}
EOF;
你可以将ob_get_contents和ob_end_clean结合到ob_get_clean中:) – NikiC 2010-09-16 19:23:54
你说的不工作呢?正如在“links.php”的内容不在$内容中?如果多数民众赞成你想要尝试使用输出流重定向(或只是读取文件)。
<?php ob_start(); include 'links.php'; $content = ob_get_contents(); ob_end_clean(); echo "contents=[$content]\n"; ?>
*叹息*每当我回答一个没有答案的问题时,在我可以完成打字之前,有3或4个答案。 – troutinator 2010-09-16 19:18:34
根本不要使用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*/?>
这将包含'links.php'的来源,而不是执行的内容。 – Rudu 2010-09-16 19:13:50
运行'file_get_contents'后不要'eval'。它不会像你期望的那样工作。原因是'include'(也就是'links.php'文件)从关闭PHP解释器开始。这就是为什么你需要' ircmaxell 2010-09-16 20:47:39