基本上,我正在为我的 CMS 编写一个模板系统,我希望有一个模块化结构,其中涉及人们放入以下标签:
<module name="news" />
or <include name="anotherTemplateFile" />
然后我想在我的 php 中找到它并用动态 html 替换。
这里有人向我指出了 DOMDocument,但我已经遇到了一个问题。
我试图找到所有<include />
在我的模板中添加标签并用一些简单的 html 替换它们。这是我的模板代码:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>CMS</title>
<include name="head" />
</head>
<body>
<include name="header" />
<include name="content" />
<include name="footer" />
</body>
</html>
这是我的 PHP:
$template = new DOMDocument();
$template->load("template/template.tpl");
foreach( $template->getElementsByTagName("include") as $include ) {
$element = '<input type="text" value="'.print_r($include, true).'" />';
$output = $template->createTextNode($element);
$template->replaceChild($output, $include);
}
echo $template->saveHTML();
现在,我得到了致命错误Uncaught exception 'DOMException' with message 'Not Found Error'
.
我查了一下,似乎是因为我的<include />
标签不一定是直接子代$template
它不会取代它们。
我怎样才能独立地更换它们?
谢谢
Tom
EDIT
基本上我有某种灵机一动。如果我为我的 PHP 做这样的事情,我会发现它正在尝试做我想做的事情:
$template = new DOMDocument();
$template->load("template/template.tpl");
foreach( $template->getElementsByTagName("include") as $include ) {
$element = '<input type="text" value="'.print_r($include, true).'" />';
$output = $template->createTextNode($element);
// this line is different:
$include->parentNode->replaceChild($output, $include);
}
echo $template->saveHTML();
然而它似乎只改变了 1 次出现<body>
我的 HTML...当我有 3 时:/