Wednesday, March 16, 2011

Validate XML using a custom DTD in PHP

Is there a way (without installing any libraries) of validating XML using a custom DTD in PHP?

From stackoverflow
  • Take a look at PHP's DOM, especially DOMDocument::schemaValidate and DOMDocument::validate.

    The example for DOMDocument::validate is fairly simple:

    <?php
    $dom = new DOMDocument;
    $dom->Load('book.xml');
    if ($dom->validate()) {
        echo "This document is valid!\n";
    }
    ?>
    
    Andrei Savu : the only way to get the validation error is to use a custom error handler. really ugly. php sucks at error handling
    Andrei Savu : http://uk3.php.net/manual/en/domdocument.schemavalidate.php#62032 looks like there is a better way than a custom error handler
  • Does this help? http://www.topxml.com/php_xml_dom/dom_document_function_validate.asp

    <?php
    
    $doc = new DomDocument;
    
    //declare file variable
    
    $file = 'C:/topxml_demo/php/xml_files/employee.xml';
    
    //declare DTD
    
    $dtd  = 'C:/topxml_demo/php/xml_files/employee.dtd';
    
    // Load the xml file into DOMDocument
    
    $doc->Load($file);
    
    //validate the DOMDocument
    
    if ($doc->validate()) {
    
        print "$file is valid against the DTD.\n";
    
     } else {
    
         print "$file is invalid against the DTD.\n";
    
     }
    
    ?>
    
    nickf : you're not using the $dtd variable anywhere there.

0 comments:

Post a Comment