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
    if($argc !== 3) {
        echo "usage: ". $argv[0] . " xmlfile xsdfile\n";
        echo "validates  xmlfile against xsdfile\n";
        die("cannot read xmlfile '{$argv[1]}'. aborting.\n");
        die("cannot read xsdfile '{$argv[2]}'. aborting.\n");
    $xmlfile = $argv[1];
    $xsdfile = $argv[2];
    echo "validating $xmlfile against $xsdfile\n";
    $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",

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