使用 Tidy 在 PHP 中验证 HTML5 文档

use*_*531 5 html php tidy

我正在尝试清理 HTML 字符串并使用 Tidy 和 PHP 创建 HTML5 文档,但是,我正在创建 HTML3.2 文档。如所见,我收到Config: missing or malformed argument for option: doctype错误。我正在 Centos 6 和 Apache 2.2 上运行 PHP 版本 5.5.35,并php_info()显示以下内容:

tidy

Tidy support    enabled
libTidy Release 14 June 2007
Extension Version   2.0 ($Id: e066a98a414c7f79f89f697c19c4336c61bc617b $)

Directive   Local Value Master Value
tidy.clean_output   no value    no value
tidy.default_config no value    no value
Run Code Online (Sandbox Code Playgroud)

如何创建 HTML5 文档?以下是我的尝试:

<?php
$html = <<<EOD
<p>Hello</p>
<div>
 <p data-customattribute="will be an error">bla</p>
 <p>bla</p>
</div>
<div>
 <p>Hi there!</p>
 <div>
  <p>Opps, a mistake</px>
 </div>
</div>
EOD;
$html="<!DOCTYPE HTML><html><head><title></title></head><body>$html</body></html>";

echo($html."\n\n");

    $config = array(
        'indent' => true,
        'indent-spaces' => 4,
        'doctype' => '<!DOCTYPE HTML>',
    );

$tidy = new tidy;
$tidy->parseString($html, $config, 'utf8');
$tidy->cleanRepair();
print_r($tidy);
Run Code Online (Sandbox Code Playgroud)

输出

<!DOCTYPE HTML><html><head><title></title></head><body><p>Hello</p>
<div>
 <p data-customattribute="will be an error">bla</p>
 <p>bla</p>
</div>
<div>
 <p>Hi there!</p>
 <div>
  <p>Opps, a mistake</px>
 </div>
</div></body></html>

tidy Object
(
    [errorBuffer] => Config: missing or malformed argument for option: doctype
line 9 column 21 - Warning: discarding unexpected </px>
line 3 column 2 - Warning: <p> proprietary attribute "data-customattribute"
    [value] => <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 3.2//EN">
<html>
    <head>
        <title></title>
    </head>
    <body>
        <p>
            Hello
        </p>
        <div>
            <p data-customattribute="will be an error">
                bla
            </p>
            <p>
                bla
            </p>
        </div>
        <div>
            <p>
                Hi there!
            </p>
            <div>
                <p>
                    Opps, a mistake
                </p>
            </div>
        </div>
    </body>
</html>
)
Run Code Online (Sandbox Code Playgroud)

Dek*_*kel 1

旧版本的 Tidy 不支持 HTML5 文档

tidy支持 HTML 5的第一个版本是在2015 年 9 月HTML Tidy Advocacy Community Group发布了 tidy-html5 的第一个版本。

请注意,您使用的是旧版本的 tidy,因此您将无法验证 html5 文档。

当前的 php 预编译版本尚未使用 tidy-html5 进行编译,因此如果您想使用 tidy-html5,则必须自己编译它。

这些说明取自tidy-html5 github 中的自述文件:

由于 PHP 源代码中的 API 更改,文件 ext/tidy/tidy.c 中的“buffio.h”需要更改为“tidybuffio.h”。

也就是说,在配置 php 之前,在 php 源目录中运行以下命令:

   sed -i 's/buffio.h/tidybuffio.h/' ext/tidy/*.c
Run Code Online (Sandbox Code Playgroud)

然后继续(这里只是一个例子,使用你自己的 php 配置选项):

   ./configure --with-tidy=/usr/local
   make
   make test
   make install
Run Code Online (Sandbox Code Playgroud)