Press "Enter" to skip to content

用Tidy优化你的HTML(Optimizing HTML with Tidy)

最近试用了很多的编辑器, 都有一个共同的缺点, 就是如果直接输入HTML,并且HTML格式错误, 有没有闭合的标签,就有可能导致最终的页面乱掉。 想了几个办法效果都不太好, 呵呵,tidy来了! 手册介绍:

  Tidy is a binding for the Tidy HTML clean and repair utility which allows you to not only clean and otherwise manipulate HTML documents, but also traverse the document tree.
    

有的时候,页面工程师给的HTML并不是很完美, 标签混乱, 结构不太容易看请, 这个时候Tidy也是可以大显身手的。
呵呵,测试如下:

<?php
ob_start();
echo <<<html
<html>
 <head>
  <title>test</title>
 </head>
 <body>
  <p>error</i>
 </body>
</html>
HTML;
$buffer = ob_get_clean();
$config = array('indent' => TRUE,
            'output-xhtml' => TRUE,
                    'wrap' => 200);
$html = tidy_parse_string($buffer, $config, 'UTF8');
$html->cleanRepair();
$html = $html->value;
print_r($html);
?>

输出 :

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <title>
      test
    </title>
  </head>
  <body>
    <p>
      error
    </p>
  </body>
</html>

错误被修正,并且加入了缩进, 呵呵,是不是看起来,整洁了很多呢?
尤其当使用在线编辑器的时候, 更是应该把用户的输入,都tidy一下,修正错误。;)

4 Comments

  1. superman
    superman July 28, 2015

    这里 sourceforge 上没找到源码都是一些二进制文件
    github 上的 htacg/tidy-html5 不知道能用不,因为编译PHP的时候需要tidy的头文件好像

  2. 雪候鸟
    雪候鸟 August 21, 2008

    kses相当于是个filter。

  3. 雪候鸟
    雪候鸟 August 20, 2008

    哦? 好,试试去

  4. feifengxlq
    feifengxlq August 19, 2008

    可以去看看kses,感觉更好。

Comments are closed.