DOMDocument::validate

(PHP 5, PHP 7, PHP 8)

DOMDocument::validate Valida o documento com base em seu DTD

Descrição

public DOMDocument::validate(): bool

Valida o documento com base em seu DTD.

Você também pode usar a propriedade validateOnParse de DOMDocument para fazer uma validação DTD.

Parâmetros

Esta função não possui parâmetros.

Valor Retornado

Retorna true em caso de sucesso ou false em caso de falha. Se o documento não tiver um DTD anexado, este método retornará false.

Exemplos

Exemplo #1 Exemplo de validação DTD

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

Você também pode validar seu arquivo XML durante o carregamento:

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

Veja Também

add a note add a note

User Contributed Notes 3 notes

up
10
a dot schaffhirt at sedna-soft dot de
15 years ago
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
up
1
cabral dot brc at gmail dot com
13 years ago
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);
    }
  }
}
?>
up
-6
darren at viamedia dot co dot za
15 years ago
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($file, LIBXML_DTDLOAD|LIBXML_DTDATTR);
// OR
// Validate against DTD
$dom->load($file, LIBXML_DTDLOAD|LIBXML_DTDVALID);
$dom->validate();
?>
To Top