Sometimes i had to validate xml files against xsd schemas. I extracted a simple cli script that shows how to do it in PHP.

(!) Note:usage: php validate-xsd.php xmlfile xsdfile
validates xmlfile against xsdfile
#!/usr/bin/php
<?php
 
    if($argc !== 3) {
        echo "usage: ". $argv[0] . " xmlfile xsdfile\n";
        echo "validates  xmlfile against xsdfile\n";
        die();
    }
 
    if(!is_readable($argv[1])){
        die("cannot read xmlfile '{$argv[1]}'. aborting.\n");
    }
 
    if(!is_readable($argv[1])){
        die("cannot read xsdfile '{$argv[2]}'. aborting.\n");
    }
 
    $xmlfile = $argv[1];
    $xsdfile = $argv[2];
 
    echo "validating $xmlfile against $xsdfile\n";
 
    libxml_use_internal_errors(true);
 
    $feed = new DOMDocument();
    $feed->preserveWhitespace = false;
    $result = $feed->load($xmlfile);
    if($result === TRUE) {
        echo "Document is well formed\n";
    } else {
        echo "Document is not well formed\n";
    }
    if(@($feed->schemaValidate($xsdfile))) {
        echo "+ Document is valid!\n";
    } else {
        echo "! Document is not valid:\n";
        // var_dump the error messages
        $errors = libxml_get_errors();
        foreach($errors as $error) {
            echo "---\n";
            printf("Error: %s \nfile: %s, line: %s, column: %s, level: %s, code: %s\n",
                $error->message,
                $error->file,
                $error->line,
                $error->column,
                $error->level,
                $error->code
            );
        }
    }

2 Responses to “PHP script for validating a XML file against a XSD Schema”

  1. mab Says:

    it is best tetorial for to validate the xml content. i have learned lot of knowledge from it.

  2. Denis Says:

    That’s OK!

    pretty good, thanks.

Leave a Reply