DOMDocument::validate

(No version information available, might be only in CVS)

DOMDocument::validate — Validates the document based on its DTD

Описание

bool DOMDocument::validate ( void )

Validates the document based on its DTD.

You can also use the validateOnParse property of DOMDocument to make a DTD validation.

Возвращаемые значения

Возвращает TRUE в случае успешного завершения или FALSE в случае возникновения ошибки. If the document have no DTD attached, this method will return FALSE.

Примеры

Пример #1 Example of DTD validation

<?php
$dom 
= new DOMDocument;
$dom->Load('book.xml');
if (
$dom->validate()) {
    echo 
"This document is valid!\n";
}
?>

You can also validate your XML file while loading it:

<?php
$dom 
= new DOMDocument;
$dom->validateOnParse true;
$dom->Load('book.xml');
?>

Коментарии

If you are loading xml with the intention of validating it against an internal dtd and you have experienced issues with the validation it could be related to missing LIBXML constants.

I found this post by "aidan at php dot net" in root level dom docs and thought it might be more useful here:
As of PHP 5.1, libxml options may be set using constants rather than the use of proprietary DomDocument properties.

DomDocument->resolveExternals is equivilant to setting
LIBXML_DTDLOAD
LIBXML_DTDATTR

DomDocument->validateOnParse is equivilant to setting
LIBXML_DTDLOAD
LIBXML_DTDVALID

PHP 5.1 users are encouraged to use the new constants.

Example:
<?php
$dom 
= new DOMDocument;
// Resolve externals
$dom->load($fileLIBXML_DTDLOAD|LIBXML_DTDATTR);
// OR 
// Validate against DTD
$dom->load($fileLIBXML_DTDLOAD|LIBXML_DTDVALID);
$dom->validate();
?>
2008-08-05 10:19:12
http://php5.kiev.ua/manual/ru/domdocument.validate.html
When validating documents with this method there are two issues I don't like about it. First, it creates a bunch of warnings, which one would not expect, as the plot of calling this method is preventing any warnings that could occur when erroneously relying on the document's validity. Second, it only returns a boolean with no chance of getting additional details about the reasons for rendering invalid.

That's the reason for me to use a little wrapper, which I post here in case anyone finds it useful.

Please note that it only works with PHP5 or later.

<?php
   
class MyDOMDocument {
        private 
$_delegate;
        private 
$_validationErrors;
       
        public function 
__construct (DOMDocument $pDocument) {
           
$this->_delegate $pDocument;
           
$this->_validationErrors = array();
        }
       
        public function 
__call ($pMethodName$pArgs) {
            if (
$pMethodName == "validate") {
               
$eh set_error_handler(array($this"onValidateError"));
               
$rv $this->_delegate->validate();
                if (
$eh) {
                   
set_error_handler($eh);
                }
                return 
$rv;
            }
            else {
                return 
call_user_func_array(array($this->_delegate$pMethodName), $pArgs);
            }
        }
        public function 
__get ($pMemberName) {
            if (
$pMemberName == "errors") {
                return 
$this->_validationErrors;
            }
            else {
                return 
$this->_delegate->$pMemberName;
            }
        }
        public function 
__set ($pMemberName$pValue) {
           
$this->_delegate->$pMemberName $pValue;
        }
        public function 
onValidateError ($pNo$pString$pFile null$pLine null$pContext null) {
           
$this->_validationErrors[] = preg_replace("/^.+: */"""$pString);
        }
    }
?>

<?php
   
// $doc is a DOMDocument object
   
$myDoc = new MyDOMDocument($doc); // copy constructor

    // do anything with $myDoc that you would with $doc

   
$isValid $myDoc->validate(); // won't create warnings
   
if (!$isValid) {
       
print_r($myDoc->errors); // the array all warnings are collected in
   
}
?>

Maybe you need to change the the part
preg_replace("/^.+: */", "", $pString)
to something different depending on your system's error reporting settings (HTML or plain text), whatsoever

Best Regards,

Anja
2008-09-17 17:22:01
http://php5.kiev.ua/manual/ru/domdocument.validate.html
I was trying to validate my SVG file just to get the IDs with getElementById(), 

<?xml version="1.0"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
<text id="text_titulo" x="150" y="20" font-family="Arial" font-size="15px" style="font-weight:bold;">Title</text>
<text id="text_subtitulo" x="200" y="35" font-family="Arial" font-size="10px">Sub Title</text>
<g transform="translate(0,50) scale(0.1)">
  <a id="a_AC" ...... >
    <polygon id="polygon_AC" ....... />
  </a>
</g>
</svg>

but when calling $dom->load(), it was getting the errors "failed to open stream" and "Validation failed: no DTD found !I/O warning : failed to load external entity"
so I created my own validation wrapper (I just want to find the IDs with getElementById() )

<?php
  $docSVG 
= new DOMDocument();
 
$docSVG->load(realpath($filepath));
 
setAllId($docSVG);

 
function 
setAllId($DOMNode){
  if(
$DOMNode->hasChildNodes()){
    foreach (
$DOMNode->childNodes as $DOMElement) {
      if(
$DOMElement->hasAttributes()){
       
$id=$DOMElement->getAttribute("id");
        if(
$id){
         
$DOMElement->setIdAttribute("id",$id);
        }
      }
     
setAllId($DOMElement);
    }
  }
}
?>
2010-09-08 15:46:45
http://php5.kiev.ua/manual/ru/domdocument.validate.html

    Поддержать сайт на родительском проекте КГБ