|
11樓 巨大八爪鱼
2016-1-15 19:01
【更新】 以下setInnerHTML函数解决了当$html未被任何节点包围时会自动产生<p>节点扰乱页面布局的问题。 function setInnerHTML($node, $html) { removeChildren($node); if (empty($html)) { return; } $doc = $node->ownerDocument; $htmlclip = new DOMDocument(); $htmlclip->loadHTML("<div>$html</div>"); $clipNode = $doc->importNode($htmlclip->getElementsByTagName('body')->item(0)->firstChild, true); while ($item = $clipNode->firstChild) { $node->appendChild($item); } }
以下setInnerHTML函数不仅解决了上面的问题,还阻止了$htmlclip自动产生HTML4文档声明部分以及head, body等多余的内容。 该函数必须在PHP版本>=5.4.0以上的服务器环境中使用。如果环境不满足的话,就用上面的函数。 function setInnerHTML($node, $html) { removeChildren($node); if (empty($html)) { return; } $doc = $node->ownerDocument; $htmlclip = new DOMDocument(); $htmlclip->loadHTML("<div>$html</div>", LIBXML_HTML_NODEFDTD | LIBXML_HTML_NOIMPLIED); $clipNode = $doc->importNode($htmlclip->firstChild, true); while ($item = $clipNode->firstChild) { $node->appendChild($item); } }
|
|
12樓 巨大八爪鱼
2016-1-15 20:50
【更新】 以下版本的setInnerHTML函数解决了中文乱码的问题。 function setInnerHTML($node, $html) { removeChildren($node); if (empty($html)) { return; } $doc = $node->ownerDocument; $htmlclip = new DOMDocument(); $htmlclip->loadHTML('<meta http-equiv="Content-Type" content="text/html;charset=utf-8"><div>' . $html . '</div>'); $clipNode = $doc->importNode($htmlclip->documentElement->lastChild->firstChild, true); while ($item = $clipNode->firstChild) { $node->appendChild($item); } }
|
|
13樓 巨大八爪鱼
2016-1-15 20:55
【以下演示如何在加载HTML模板文件时自动用gettext翻译其中的文本内容,以及之后如何用sprintf替换其中的变量】 【translate_example.php】 <?php libxml_use_internal_errors(true);
# 模拟gettext的_()函数 function ____($text) { switch ($text) { case 'Untitled Document': return '无标题文档'; case 'Article Example': return '文章示例'; case 'This HTML tutorial contains %d HTML examples.': return '这个HTML教程中包含了%d个HTML示例。'; case 'There are %s options in total.': return '共有%s个选项。'; case 'Apple': return '苹果'; case 'Orange': return '橘子'; case 'Link Example': return '示例链接'; case "\r\nWith our online ": return "\r\n使用我们的在线"; case 'HTML editor': return 'HTML编辑器'; case ', you can edit the HTML, and click on a button to view the result.': return ',您可以编辑HTML代码,并且点击按钮后就能看到运行结果。'; case 'Time Elapsed: ': return '消耗的时间:'; default: return $text; # 不能翻译的文字 } }
function translate($doc) { $path = new DOMXPath($doc); $textNodes = $path->query('/descendant::*/text()'); for ($i = 0; $i < $textNodes->length; $i++) { $value = $textNodes->item($i)->nodeValue; if (trim($value) == '') { continue; } $textNodes->item($i)->nodeValue = ____($value); } }
function removeChildren($node) { while ($node->childNodes->length > 0) { $node->removeChild($node->firstChild); } }
function setInnerHTML($node, $html) { removeChildren($node); if (empty($html)) { return; } $doc = $node->ownerDocument; $htmlclip = new DOMDocument(); $htmlclip->loadHTML('<meta http-equiv="Content-Type" content="text/html;charset=utf-8"><div>' . $html . '</div>'); $clipNode = $doc->importNode($htmlclip->documentElement->lastChild->firstChild, true); while ($item = $clipNode->firstChild) { $node->appendChild($item); } }
$doc = new DOMDocument(); $doc->loadHTMLFile('template_example.html'); $doc->formatOutput = true;
translate($doc); # 翻译HTML模板中的文字
# 选中第二个单选框 $path = new DOMXPath($doc); $radios = $path->query('/html/body/form/input'); $radios->item(1)->setAttribute('checked', 'checked');
# 显示选项数量 $pNode = $doc->getElementById('CountExamples'); $pNode->firstChild->nodeValue = sprintf($pNode->firstChild->nodeValue, $radios->length); # $pNode指向<p>,firstChild指向<p>中的文本节点 # 最好不要直接设置<p>的nodeValue的值,这样可能会导致两个相邻的<p>节点被合并而破坏页面布局 $pNode = $doc->getElementById('CountOptions'); setInnerHTML($pNode, sprintf($pNode->firstChild->nodeValue, '<span style="color:red">' . $radios->length . '</span>'));
echo html_entity_decode($doc->saveHTML(), ENT_QUOTES, 'utf-8');
/* PHP DOM不能识别HTML5的<meta charset="utf-8">标签 但是能够识别HTML4的<meta http-equiv="Content-Type" content="text/html;charset=utf-8"> 所以在输出的时候要使用html_entity_decode函数防止源文件中的中文被转换成HTML Entity表示。 */
【HTML模板:template_example.html】 <!doctype html> <html> <head> <meta charset="utf-8"> <title>Untitled Document</title> <style> body { font-family: Arial; font-size: 12px; } mark { background-color: #F9F9F9; border: 1px solid #DDDDDD; border-radius: 2px; font-family: monospace, Courier; padding: 1px 4px; } p { line-height: 1.5em; margin: 3px 0px; }
footer { background-color: #EEEEEE; font-size: 13px; margin-top: 20px; padding: 10px 0px; text-align: center; } footer span { color: red; }
ul { margin: 2px 0px; padding-left: 16px; }
ul.Navigator { background-color: #5F5F5F; font-family: "Segoe UI", Arial, sans-serif; letter-spacing: 1px; list-style: none; padding-left: 0px; overflow: hidden; }
ul.Navigator li { float: left; }
ul.Navigator a { color: white; display: inline-block; font-size: 17px; padding: 10px 15px 9px; text-decoration: none; } ul.Navigator a:hover { background-color: black; } ul.Navigator a.active { background-color: #73AF21; }
form { padding: 5px 0px; } </style> </head>
<body> <nav> <ul class="Navigator"> <li><a class="active" href="?language=HTML">HTML</a></li> <li><a href="?language=CSS">CSS</a></li> <li><a href="?language=JavaScript">JAVASCRIPT</a></li> </ul> </nav> <article> <h1>Article Example</h1> <p id="CountExamples">This HTML tutorial contains %d HTML examples.<br> With our online <mark>HTML editor</mark>, you can edit the HTML, and click on a button to view the result.</p> <ul> <li><a href="example">Link Example</a></li> </ul> </article> <form id="form1" name="form1" method="post"> <input type="radio" name="radio" id="radio" value="apple"><label for="radio">Apple</label><br> <input type="radio" name="radio" id="radio2" value="orange"><label for="radio2">Orange</label> </form> <p id="CountOptions">There are %s options in total.</p> <footer>Time Elapsed: <span></span></footer> </body> </html>
|
|
14樓 巨大八爪鱼
2016-1-15 20:57
【运行效果】
|
|
15樓 巨大八爪鱼
2016-1-15 20:59
由于HTML模板文件中的文字仍是英文,所以在Dreamweaver的设计视图中仍然能够看到这些文字,方便编辑。 如果只用PHP的代码块(例如<?=_('Orange')?>),那么在设计视图中就只能看到PHP块标记 ,十分影响网页设计。
|
|
16樓 巨大八爪鱼
2016-1-15 21:01
【HTML输出内容】 <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>无标题文档</title> <style> body { font-family: Arial; font-size: 12px; } mark { background-color: #F9F9F9; border: 1px solid #DDDDDD; border-radius: 2px; font-family: monospace, Courier; padding: 1px 4px; } p { line-height: 1.5em; margin: 3px 0px; }
footer { background-color: #EEEEEE; font-size: 13px; margin-top: 20px; padding: 10px 0px; text-align: center; } footer span { color: red; }
ul { margin: 2px 0px; padding-left: 16px; }
ul.Navigator { background-color: #5F5F5F; font-family: "Segoe UI", Arial, sans-serif; letter-spacing: 1px; list-style: none; padding-left: 0px; overflow: hidden; }
ul.Navigator li { float: left; }
ul.Navigator a { color: white; display: inline-block; font-size: 17px; padding: 10px 15px 9px; text-decoration: none; } ul.Navigator a:hover { background-color: black; } ul.Navigator a.active { background-color: #73AF21; }
form { padding: 5px 0px; } </style> </head> <body> <nav><ul class="Navigator"> <li><a class="active" href="?language=HTML">HTML</a></li> <li><a href="?language=CSS">CSS</a></li> <li><a href="?language=JavaScript">JAVASCRIPT</a></li> </ul></nav><article><h1>文章示例</h1> <p id="CountExamples">这个HTML教程中包含了2个HTML示例。<br> 使用我们的在线<mark>HTML编辑器</mark>,您可以编辑HTML代码,并且点击按钮后就能看到运行结果。</p> <ul> <li><a href="example">示例链接</a></li> </ul></article><form id="form1" name="form1" method="post"> <input type="radio" name="radio" id="radio" value="apple"><label for="radio">苹果</label><br><input type="radio" name="radio" id="radio2" value="orange" checked><label for="radio2">橘子</label> </form> <p id="CountOptions">共有<span style="color:red">2</span>个选项。</p> <footer>消耗的时间:<span></span></footer> </body> </html>
|
|
17樓 巨大八爪鱼
2016-2-10 22:52
【示例代码】用面向对象的方法来实现上述内容: 【ExamplePage.php】 <?php class ExamplePage extends HTMLPage { private $startTime; function __construct() { $this->startTime = microtime(); parent::__construct('template_example.html'); $this->title = 'My Test Page'; $this->changeTabs(); $this->showArticles(); $this->showFooter(); } private function changeTabs() { $this->setActiveTab('/nav/ul/li/a', 1); // 选中第二个选项卡 $this->setText('/nav/ul/li[1]/a', 'HTML5'); $this->setText('/nav/ul/li[2]/a', 'CSS3'); $this->setInnerHTML('/nav/ul/li[3]/a', '<b style="color:red">Java</b>Script'); } private function showArticles() { $t_article = $this->queryBody('/article'); for ($i = 1; $i <= 4; $i++) { $article = $this->duplicate($t_article); $this->setChildText($article, 'h1', "Article $i"); $this->setChildHTML($article, 'p', "This is a <mark>paragraph</mark> of Article $i..."); $t_link = $this->queryIn('ul/li', $article); for ($j = 1; $j <= 5; $j++) { $link = $this->duplicate($t_link); $n = ($i - 1) * 5 + $j; $this->setChildText($link, 'a', "Link $j")->setAttribute('href', "page$n.php"); //$this->setChildAttribute($link, 'a', 'href', 'anotherpage.php'); } $this->delete($t_link); } $this->delete($t_article); } private function showFooter() { $str = number_format(microtime() - $this->startTime, 3) . 's'; $this->setText('/footer/span', $str); } }
|
|
18樓 巨大八爪鱼
2016-2-10 22:52
【访问页:example.php】 <?php libxml_use_internal_errors(true); include_once('HTMLPage.php'); include_once('ExamplePage.php'); $page = new ExamplePage(); $page->show();
|
|
19樓 巨大八爪鱼
2016-2-10 22:53
【封装的HTMLPage基类:HTMLPage.php】 <?php class HTMLPage extends DOMDocument { private $path; function __construct($template) { $this->loadHTMLFile($template); $this->path = new DOMXPath($this); } function __get($property) { if ($property == 'title') { return $this->queryHead('/title', 0)->nodeValue; } } function __set($property, $value) { if ($property == 'title') { $this->queryHead('/title', 0)->nodeValue = $value; } } public function delete($node) { if (is_string($node)) { $node = $this->queryBody($node, 0); } elseif ($node instanceof DOMNodeList) { $node = $node->item(0); } return $node->parentNode->removeChild($node); } public function duplicate($templateNode) { if ($templateNode instanceof DOMNodeList) { $templateNode = $templateNode->item(0); } return $templateNode->parentNode->insertBefore($templateNode->cloneNode(true), $templateNode); } public function getInnerHTML(DOMNode $element) { $innerHTML = ''; foreach ($element->childNodes as $child) { $innerHTML .= $element->ownerDocument->saveHTML($child); } return $innerHTML; } public function query($path, $item = NULL) { if (is_null($item)) { return $this->path->query($path); } else { return $this->path->query($path)->item($item); } } public function queryBody($path, $item = NULL) { return $this->query("/html/body$path", $item); } public function queryHead($path, $item = NULL) { return $this->query("/html/head$path", $item); } public function queryIn($path, $node, $item = NULL) { if (is_string($node)) { $node = $this->queryBody($node); } if (is_null($item)) { return $this->path->query(".//$path", $node); } else { return $this->path->query(".//$path", $node)->item($item); } } public function removeChildren($node) { while ($node->childNodes->length > 0) { $node->removeChild($node->firstChild); } } public function setActiveTab($nodeList, $index) { if (is_string($nodeList)) { $nodeList = $this->queryBody($nodeList); } $nodeList->item(0)->removeAttribute('class'); $nodeList->item($index)->setAttribute('class', 'active'); } public function setChildAttribute($node, $path, $attribute, $value) { $node = $this->queryIn($path, $node, 0); $node->setAttribute($attribute, $value); return $node; } public function setChildText($node, $path, $text) { $node = $this->queryIn($path, $node, 0); $node->nodeValue = $text; return $node; } public function setChildHTML($node, $path, $html) { $node = $this->queryIn($path, $node, 0); $this->setInnerHTML($node, $html); return $node; } public function setInnerHTML($node, $html) { if (is_string($node)) { $node = $this->queryBody($node, 0); } $this->removeChildren($node); if (empty($html)) { return; } $doc = $node->ownerDocument; $htmlclip = new DOMDocument(); $htmlclip->loadHTML('<meta http-equiv="Content-Type" content="text/html;charset=utf-8"><div>' . $html . '</div>'); $clipNode = $doc->importNode($htmlclip->documentElement->lastChild->firstChild, true); while ($item = $clipNode->firstChild) { $node->appendChild($item); } } public function setText($node, $text) { if (is_string($node)) { $node = $this->queryBody($node, 0); } $node->nodeValue = $text; } public function show() { echo $this->saveHTML(); } }
|
|
20樓 巨大八爪鱼
2016-2-10 22:53
【最终输出页面】
|