validate a xml file against a xsd using php

前端 未结 3 490
误落风尘
误落风尘 2021-02-04 02:05

how to validate a xml file against a xsd? there is domdocument::schemaValidate() but It does not tell where are the errors. is there any class for that? does it have any worth m

3条回答
  •  灰色年华
    2021-02-04 02:33

    User contrib from http://php.net/manual/en/domdocument.schemavalidate.php

    It works like a charm!

    For more detailed feedback from DOMDocument::schemaValidate, disable libxml errors and fetch error information yourself. See http://php.net/manual/en/ref.libxml.php for more info.

    example.xml

    
    
        This is an example.
        Error condition.
    
    

    example.xsd

    
    
        
            
                
                    
                    
                
            
        
    
    

    PHP

    \n";
        switch ($error->level) {
            case LIBXML_ERR_WARNING:
                $return .= "Warning $error->code: ";
                break;
            case LIBXML_ERR_ERROR:
                $return .= "Error $error->code: ";
                break;
            case LIBXML_ERR_FATAL:
                $return .= "Fatal Error $error->code: ";
                break;
        }
        $return .= trim($error->message);
        if ($error->file) {
            $return .=    " in $error->file";
        }
        $return .= " on line $error->line\n";
    
        return $return;
    }
    
    function libxml_display_errors() {
        $errors = libxml_get_errors();
        foreach ($errors as $error) {
            print libxml_display_error($error);
        }
        libxml_clear_errors();
    }
    
    // Enable user error handling
    libxml_use_internal_errors(true);
    
    $xml = new DOMDocument();
    $xml->load('example.xml');
    
    if (!$xml->schemaValidate('example.xsd')) {
        print 'DOMDocument::schemaValidate() Generated Errors!';
        libxml_display_errors();
    }
    
    ?>
    

提交回复
热议问题