0

我的 index.php 中有这行代码:

<?php include ("header.php"); ?>
    </body>
</html>

我的 header.php:

<!DOCTYPE html>

<html lang="en">
<head>
    <?php include("php/dynamic_header.php"); ?>
    <meta charset="utf-8">
    <meta name="description" content="Write a description" /> 
    <meta name="keywords" content="Your keywords here" /> 
    <title>Random Title</title>
</head>
<body>
    <header>This is my header</header>

还有我的dynamic_header.php:

$dom = new domDocument;
@$dom->loadHTMLFile("header.php");

$meta = $dom->getElementsByTagName('meta')->item(1);
$meta->setAttribute('content','new description');
$dom->saveHTML();

但是,当我使用 saveHTML() 时,什么也没有发生。我尝试使用:

echo $dom->saveHTML();

但这会产生两个标题,所以有人可以解释一下我做错了什么吗?基本上,我正在尝试使用 PHP DOM 更改元标记上的属性,但是如果不复制标题,我就无法保存它。

4

1 回答 1

0

它应该同样有效,saveHTMLFile()这就是为什么我认为您的文件权限有问题或者不允许您保存数据的原因。无论哪种方式,我认为你做错了你应该使用模板库而不是使用 DOMDocument 修改数据。

例如,使用Smarty,您可以像这样做一个标题模板:

<!DOCTYPE html>

<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="description" content="{$description|default:"Write a description"}" /> 
    <meta name="keywords" content="Your keywords here" /> 
    <title>{$title|default:"Default Page Title"}</title>
</head>
<body>

这是相关的测试代码,表明它不会使用 DOMDocument 创建重复项:

<?php
$str = <<<DATA
<!DOCTYPE html>

<html lang="en">
<head>
    <?php include("php/dynamic_header.php"); ?>
    <meta charset="utf-8">
    <meta name="description" content="Write a description" /> 
    <meta name="keywords" content="Your keywords here" /> 
    <title>Random Title</title>
</head>
<body>
    <header>This is my header</header>
DATA;

$dom = new domDocument;
@$dom->loadHTML($str);
$dom->formatOutput = true;
$dom->preserveWhitespace = false;

$meta = $dom->getElementsByTagName('meta')->item(1);
$meta->setAttribute('content','new description');
echo $dom->saveHTML();
于 2014-03-02T21:48:41.033 回答