简体   繁体   English

PHP中的HTML标记操作

[英]HTML markup manipulation in PHP

Working with PHP DOM - html manipulation. 使用PHP DOM-html操作。 It's really very effective way to output HTML markup (at least, prevents mess of logic and markup in code). 这是输出HTML标记的一种非常有效的方法(至少可以防止代码中的逻辑和标记混乱)。

But, to generate 50 line of html markup, one must write about 200 lines in PHP :( . 但是,要生成50行html标记,必须在PHP中编写约200行:(。

Example piece of code: 代码示例:

... ...

$signup_form = $document->createElement('form');
$signup_form->setAttribute('id', 'signup_form');
$signup_form->setAttribute('action', 'registration/signup.php');
$signup_form->setAttribute('method', 'post');
$su_fname_label = $document->createElement('label');
$su_fname_label->setAttribute('for', 'fname');
$su_fname_label_content = $document->createTextNode('Name');
$su_fname_label->appendChild($su_fname_label_content);
$su_fname_textbox = $document->createElement('input');
$su_fname_textbox->setAttribute('name', 'fname');
$su_fname_textbox->setAttribute('class', 'valid');
$su_fname_textbox->setAttribute('placeholder', 'Please enter your name');
$su_fname_textbox->setAttribute('type', 'text');

... ...

As you see, It's only 1 element of form. 如您所见,它只是表单的1个元素。 Imagine, If there are 5 elements in HTML form, php code will be huge. 想象一下,如果HTML表单中有5个元素,php代码将是巨大的。 I wonder, is there any way to minify for ex. 我想知道,是否有任何方法可以缩小规模。 by setting multiple attributes at once? 通过一次设置多个属性? Any suggestions? 有什么建议么?

Why don't you just output HTML and enabled output buffering. 为什么不只输出HTML并启用输出缓冲。 Then you can filter out the output using the tidy extension and be sure that your output HTML is valid, while still going as fast as writing pure HTML. 然后,您可以使用tidy扩展名过滤输出,并确保您的输出HTML有效,同时仍能像编写纯HTML一样快。

Despite the above, as @Gordon suggests: 尽管有上述情况,如@Gordon所建议:

tidy is hardly suitable for programmatically authoring (x)html. 整洁几乎不适合以编程方式编写(x)html。 its more like a post processor. 它更像是后处理器。

What is your reason for using the DOM to generate html output? 您使用DOM生成html输出的原因是什么? There's no way to make the DOM terse ! 没有办法使DOM 简洁

Usually you just use PHP for templating. 通常,您只使用PHP进行模板制作。 Create a separate file like so: 创建一个单独的文件,如下所示:

<?php // template.php
echo '<!DOCTYPE html>',"\n";
?>
<html>
    <head>
    <meta charset="utf-8">
    <title><?=htmlspecialchars($title, ENT_NOQUOTES, 'utf-8')?></title>
    </head>
    <body>
       <form id="signup_form" action="registration/signup.php" method="post">
           <label for="fname">Name</label>
           <input id="fname" name="fname" class="valid" placeholder="Please enter your name" type="text">
       </form>
    </body>
</html>

Then using a template function: 然后使用模板函数:

function render($__filename, $__data) {
    extract($__data, EXTR_SKIP);
    ob_start();
    include $__filename;
    return ob_get_clean();
}

Render your template from your code like so: 从代码中渲染模板,如下所示:

do_something();
$templatedata = array('title'=>'The Title');
$html = render('template.php', $templatedata);

If you want something that is node-aware (which is a great idea for ensuring well-formedness and proper escaping!), you can use XSLT or a third-party template engine like PHPTAL . 如果您想要某种可感知节点的东西(这是确保格式正确和正确转义的好主意!),则可以使用XSLT或第三方模板引擎(如PHPTAL)

I used to do what you're doing until I realized that it's not very readable. 我曾经做过您正在做的事情,直到我意识到它不是很可读。 You have to analyze the code to determine what markup is being built. 您必须分析代码以确定正在构建的标记。 It's also harder to maintain. 它也很难维护。 As you said, adding a single field to a form requires quite a bit of code and making changes requires digging through all that code. 如您所说,向表单添加单个字段需要大量代码,而进行更改则需要挖掘所有这些代码。 I agree with wanting to keep your PHP logic separate from your markup; 我同意希望将您的PHP逻辑与标记分开; however, there are better ways to keep your code clean depending on what you're trying to do. 但是,有更好的方法可以使代码保持整洁,具体取决于您要执行的操作。

Without getting into third-party solutions you could: 无需使用第三方解决方案,您可以:

  1. Load markup from a separate file into a DOM object for further manipulation. 将标记从单独的文件加载到DOM对象中,以进行进一步操作。

  2. Use PHP as the template engine it was designed to be by embedding PHP in your markup. 将PHP用作模板引擎,其目的是通过将PHP嵌入标记中而设计的。 As Col. Shrapnel explains quite eloquently: “[E]mbedded PHP lets you separate business logic from presentation logic on a site-wide basis, supporting templates of any size and structure…”. 正如Shrapnel上校非常雄辩地解释:“ [E]嵌入式PHP使您可以在整个站点范围内将业务逻辑与表示逻辑分开,支持任何大小和结构的模板……”。

  3. Assign markup to a variable using heredoc syntax . 使用heredoc语法将标记分配给变量。 While not the best choice, it's much easier to read than a purely DOM-based approach. 尽管不是最佳选择,但比纯粹基于DOM的方法更容易阅读。

$signup_form = <<<EndHTMLForm
<form id="signup_form" action="registration/signup.php" method="post">
    <label for="fname">Name</label>
    <input name="fname" class="valid" placeholder="Please enter your name" type="text">
</form>
EndHTMLForm;

My purpose here isn't to steer you away from third-party solutions, but to illustrate alternative approaches in plain-vanilla PHP. 我的目的不是要引导您脱离第三方解决方案,而是要说明纯净的PHP中的替代方法。 The DOM is verbose. DOM是冗长的。 It certainly has wonderful advantages, but creating markup from scratch isn't one of them. 它当然具有奇妙的优势,但是从头创建标记并不是其中之一。

Depending on your need for speed and if you're able to use caching and the like, a library such as phpQuery could be of use. 根据您对速度的需求以及是否能够使用缓存等,可以使用诸如phpQuery之类的库。

It's a "port" of kind of jQuery to PHP and has the same versatility and simplicity as jQuery . 它是jQuery到PHP的一种“端口”,具有与jQuery相同的通用性和简单性。 However, in my experience, it's not quite as fast as I should like in generating the code (I have not , however, conducted any thorough tests, it's just a feeling). 但是,以我的经验,生成代码的速度并没有我想要的那么快(但是,我还没有进行任何彻底的测试,只是一种感觉)。

The code you've given as an example could be expressed along these lines with phpQuery ( untested ): 您作为示例给出的代码可以使用phpQuery未测试 )沿着这些行表示:

$form = pq ('<form />')
          ->attr (array (
                    'id' => 'signup_form',
                    'action' => 'registration/signup.php',
                    'method' => 'POST',
                  ));
$label = pq ('<label />')
          ->html ('Name')
          ->attr ('for', 'fname')
          ->appendTo ($form);
$text = pq ('<input />')
          ->attr (array (
                    'name' => 'fname',
                    'data-placeholder' => 'Please enter your name',
                    'type' => 'text',
                  ))
          ->addClass ('valid')
          ->appendTo ($label);

I've written it with the formatting I prefer, and it's slightly more lines than in the code you've supplied; 我已经按照自己喜欢的格式编写了代码,而且比您提供的代码多了几行。 but it could easily be reduced to 5-10 or so lines with maintained readability, if you prefer more compact coding. 但如果您希望使用更紧凑的编码,则可以很容易地将其减少到5-10左右行,并保持可读性。 At any rate, I find it quite a lot easier to read and you don't have to write quite so much DOM code in order to generate quite a lot of HTML code. 无论如何,我发现它很容易阅读,而且您不必编写太多DOM代码即可生成大量HTML代码。

Also, given that phpQuery uses the same wrapping concept as jQuery , an unwrapped node, for instance $form in the above code, is a regular DOMNode unless wrapped in pq() . 同样,鉴于phpQuery使用与jQuery相同的包装概念,未包装的节点(例如,上面代码中的$form是常规的DOMNode除非包装在pq() This gives you a lot of flexibility to either use phpQuery 's convenience routines, or the more "fundamental" functionality of PHP DOM . 这为您提供了很大的灵活性,既可以使用phpQuery的便利例程,也可以使用PHP DOM的更多“基本”功能。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM