saveHTML()无法正常工作

时间:2014-03-02 09:22:47

标签: php dom include php-include

我在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更改元标记上的属性,但是我无法在不重复标题的情况下保存它。

1 个答案:

答案 0 :(得分: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();