PHP实现通过XSD校验XML

858 阅读1分钟

今天在翻查资料找到用PHP实现通过XSD校验XML,这对于日常工作是顶好的呀。**参考文章:www.codementor.io/@sirolad/va…~

亲测OK,代码贴上:

class DOMValidator
{
    public $feedSchema;

    public $feedErrors = 0;

    public $errorDetails;

    public function __construct()
    {
        $this->handler = new \DOMDocument('1.0', 'utf-8');
    }

    /**
     * 组装错误信息
     * @return string
     */
    private function libxmlDisplayError($error)
    {
        $errorString = "错误码: $error->code" ." ," ." 文件:$error->file (行:{$error->line}):";
        $errorString .= trim($error->message);
        return $errorString;
    }

    /**
     * 组装错误信息
     * @return array
     */
    private function libxmlDisplayErrors()
    {
        $errors = libxml_get_errors();
        $result = [];
        foreach ($errors as $error) {
            $result[] = $this->libxmlDisplayError($error);
        }
        libxml_clear_errors();
        return $result;
    }

    /**
     * 验证过程
     */
    public function validateFeeds($feeds)
    {
        if (!class_exists('DOMDocument')) {
            throw new \DOMException("'DOMDocument' class not found!");
            return false;
        }
        if (!file_exists($this->feedSchema)) {
            throw new \Exception('Schema is Missing, Please add schema to feedSchema property');
            return false;
        }
        libxml_use_internal_errors(true);
        if (!($fp = fopen($feeds, "r"))) {
            die("could not open XML input");
        }
        $contents = fread($fp, filesize($feeds));
        fclose($fp);

        $this->handler->loadXML($contents, LIBXML_NOBLANKS);
        if (!$this->handler->schemaValidate($this->feedSchema)) {
            $this->errorDetails = $this->libxmlDisplayErrors();
            $this->feedErrors = 1;
        } else {
            return true;
        }
    }

    /**
     * 输出错误
     */
    public function displayErrors()
    {
        return $this->errorDetails;
    }

}


/**
 * 使用
 */
$validator = new DOMValidator;

//选择xsd文件
$validator->feedSchema = __DIR__ . '/export.xsd';

$validated = $validator->validateFeeds('CEB603Message.xml');
if ($validated) {
    echo "格式校验通过";
} else {
    print_r($validator->displayErrors());
}