W3C验证PHP类
如果要将W3C验证检查合并到应用程序中,则可以使用以下类。它用于file_get_contents()获取文件的内容,然后使用正则表达式返回错误数或如果发生任何错误则返回-1。当然,如果文档有效,该函数将返回0。
url = $url;
}
/**
* Get the results from the W3C validation site and use regular expressions to return a result.
*
* @return integer The number of errors, or -1 if an error was encountered.
*/
public function getValidation(){
$w3cvalidator = strip_tags(file_get_contents("http://validator.w3.org/check?uri=".$this->url));
//验证者响应为空
if ( $w3cvalidator == '' ) {
$this->result = -1;
return $this->result;
}
//验证程序响应,检查结果
preg_match_all('/(?<=Result:)\s+(\d)*(?= errors?)/i', $w3cvalidator, $matches);
if ( isset($matches[0][0]) ) {
$this->result = trim($matches[0][0]);
return $this->result;
}
//检查损坏的文件
preg_match_all('/Sorry! This document can not be checked\./i', $w3cvalidator, $matches);
if ( isset($matches[0][0]) ) {
$this->result = -1;
return $this->result;
}
//文件有效
$this->result = 0;
return $this->result;
}
}您可以像这样使用该类:
$w3c = new W3cValidate("http://www.nhooo.com");
echo $w3c->getValidation();
$w3c = new W3cValidate("http://www.amazon.co.uk");
echo $w3c->getValidation();#的第一个结果!代码返回0个错误,而AmazonUK的第二个结果返回1,565个错误。我以Amazon为例,因为我知道有很多HTML错误。
您可以从W3C站点下载W3C验证代码并将其安装在自己的服务器上,但是该代码库是用perl编写的。此类旨在用作获得W3C验证结果的捷径,而无需将其集成到您的PHP应用程序中。
关于本课程,还有两点要记住。首先,W3C有可能会更改其页面上的输出,从而更改返回的结果。这实际上会破坏类,因此偶尔检查一下结果总是很有用的。其次,如果您使用此类做过多的事情,您会发现自己因使用过多而被阻止访问W3C验证站点。