views:

3861

answers:

2

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

+3  A: 

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";
}
?>
owenmarshall
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
Andrei Savu
A: 

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";

 }

?>
Nikki9696
you're not using the $dtd variable anywhere there.
nickf