PHP: building (X)HTML output with DOM - pros and cons?

牧云@^-^@ 提交于 2019-12-06 07:03:29

问题


I just started out with a new site and I decided to use DOMImplementation for building the complete site.

What do you think about this, is it fast enough? I expect it to be quite a bit slower than the basic print method. I prefer the DOM one because it allows greater flexibility when building the final output, not to mention the more error-free XHTML. Anyway, I would like to have some speed comparision at least.

Could you recommend me any (perhaps completely obvious) ideas to keep the PHP code clean (i.e. keep the HTML on a minimum level)?


回答1:


Is it fast enough? That totally depends on your site, of course. For a trivial or prototype site it'd be fine, but I certainly wouldn't want to deploy a DOM-templating solution on a complex, high-traffic site.

You won't be able to generate HTML-compatible-XHTML this way; you'll have to choose between saveXML which produces pure, non-IE-compatible XHTML, and saveHTML, which creates HTML4. CDATA elements like style and script may also need some attention.

DOM calls are also very verbose for content creation, like creating nodes in JavaScript without the benefit of helper functions or frameworks. I'm not sure the resulting code is going to be that readable, in comparison to PHP templating.

You can make PHP templating ‘cleaner’ in a simpler way by using a consistent markup tree, treating PHP structures like <?php if (condition) { ?> ... <?php } ?> as if they were XML start and end tags, and always nesting and indenting them consistently in the ‘well-formed’ style. See eg. this question for some discussion.




回答2:


You could have a Widget class that has methods like checkBox, textArea, and the like. Your View/Controller base class defines a function addContent($aString). When you build a form, you say stuff like

$builder = new Widget();
$this->addContent($builder->textArea("Description", $description, 5, 100);
$this->addContent($builder->radioGroup("Platform", array("FreeBSD", "Linux", "Windows"), $platform, 100);

where

public function textArea($name, $value, $numLines, $width) {...}
public function radioGroup($title, $nameArray, $selectedValue, $width0 {...}
// etc.

Your forms then don't know anything about HTML then: they operate strictly with UI components. Subclasses of your Widget class might produce HTML, or whatever.



来源:https://stackoverflow.com/questions/2371037/php-building-xhtml-output-with-dom-pros-and-cons

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!