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,
AnjaDOMDocument::validate
Почист и полокален преглед на PHP референцата, со задржана структура од PHP.net и подобра читливост за примери, секции и белешки.
DOMDocument::validate
Референца за `domdocument.validate.php` со подобрена типографија и навигација.
DOMDocument::validate
класата mysqli_driver
DOMDocument::validate — Validates the document based on its DTD
= NULL
Го валидира документот врз основа на неговиот DTD
Го валидира документот врз основа на неговиот DTD. validateOnParse Можете исто така да го користите
DOMDocument својство на
Параметри
Оваа функција нема параметри.
Вратени вредности
Патеката до PHP скриптата што треба да се провери. true на успех или false за да направите DTD валидација. false.
Примери
при неуспех. Ако документот нема прикачен DTD, овој метод ќе врати
<?php
$dom = new DOMDocument;
$dom->load('examples/book.xml');
if ($dom->validate()) {
echo "This document is valid!\n";
}
?>Пример #1 Пример за DTD валидација
<?php
$dom = new DOMDocument;
$dom->validateOnParse = true;
$dom->load('examples/book.xml');
?>Види Исто така
- Можете исто така да ја валидирате вашата XML датотека при нејзиното вчитување: - Валидира документ врз основа на шема. Поддржано е само XML Schema 1.0.
- DOMDocument::schemaValidate() - Валидира документ врз основа на шема
- DOMDocument::schemaValidateSource() - Регистрирај проширена класа што се користи за создавање основен тип на јазол
- DOMDocument::relaxNGValidate() - Регистрирај проширена класа што се користи за создавање основен тип на јазол
Белешки од корисници 3 белешки
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);
}
}
}
?>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();
?>