【发布时间】:2011-07-14 03:17:56
【问题描述】:
基本上,我正在为我的 CMS 编写一个模板系统,我希望有一个模块化结构,其中涉及人们放入如下标签:
<module name="news" /> 或 <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 的直接子代,它不会替换它们。
如何独立于血统替换它们?
谢谢
汤姆
编辑
基本上我有某种脑电波。如果我为我的 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();
但是,当我有 3 个时,它似乎只更改了我的 HTML 的 <body> 中的 1 个出现。:/
【问题讨论】:
-
尝试使用simplehtmldom.sourceforge.net 代替 DOMDocument
-
@yoda 你告诉他用钝黄油刀代替手术刀
-
simplehtmldom 吃掉我从未见过的记忆
-
@Thomas 您的代码将不起作用,因为
createTextNode()将转义任何尖括号。请改用appendXML() -
谢谢戈登。 :) 那时会在那个障碍上绊倒。但是现在的问题是它根本没有取代它们......
标签: domdocument php