输出缓冲 - PHP - 如何在包含标头.php后更改页面的元内容


output buffering - PHP - how to change meta contents of the page AFTER including header.php?

Page.php

<?ob_start():
include('header.php');
?>
<? $pageTitle='Page';
echo 'body html';
?>
<?
$pg=ob_get_contents();
ob_end_clean();
echo str_replace('<!--TITLE-->',$pageTitle,$pg);
?>

标头.php

<!-- Basic -->
<title><!--TITLE--> | DEMO</title>
<!-- Page Description and Author -->
<meta name="description" content="">
<meta name="author" content="">
在页面

顶部插入标题.php文件后.php如何在我的页面中包含元描述内容和作者内容以及其他元名称?

与其使用某种字符串操作在某处插入文本,不如构建您的应用程序,以便您的业务逻辑首先运行,然后运行模板代码。在写出任何内容之前,弄清楚您希望标题和其他元数据是什么。

如果你不喜欢修改头文件..你可以执行以下操作...但我建议你使你的代码结构比这个更好:(它需要更加动态

<?php
ob_start();
include('header.php');
$pageTitle='Page';
echo 'body html';
$pg=ob_get_contents();

$description = 'your description';
$author = 'your author';

//delete old desc and author
$pg = str_replace('content=""', '', $pg);
//add anew desc and author
$pg = str_replace('name="description"', 'name="description" content="'.$description.'" ', $pg);
$pg = str_replace('name="author"', 'name="author" content="'.$author.'" ', $pg);
ob_end_clean();
echo str_replace('<!--TITLE-->',$pageTitle,$pg);

?>

您可以在ob_start中定义回调函数 ob_start网页的示例 #1 中记录

了调用。
function modify_header($buffer)
{
  // do your changes in $buffer here
}
ob_start(modify_header);

无论如何,我建议使用一些模板框架来完成所有这些工作

所以我知道你必须用 html 内容 php 文件,你想将"header.php"的元"描述"和"作者"复制到"page.php"。

通过 php 获取 html 内容是不可能的。您可以在变量中保护元"描述"和"作者",并将元写入"header.php"并将这些变量发送到"page.php

标头.php:

<html>
<head>
<title>DEMO</title>
<?php
$description = '...';
$author = 'me';
echo '<meta name="description" content="'.$description.'">';
echo '<meta name="author" content="'.$author.'">';
function getDescription(){
    return $description;
}
function getAuthor(){
    return $author;
}
?>
</head>
<body>...</body>
</html>

页.php:

<html>
<head>
<title>DEMO</title>
<?php
$description = getDescription();
$author = getAuthor();
echo '<meta name="description" content="'.$description.'">';
echo '<meta name="author" content="'.$author.'">';
?>
</head>
<body>...</body>
</html>