我已经经历了大约10个其他线程,但没有看到有关此实际问题的任何信息。我所期望的错误,但我希望能够输出它给出的错误。我知道我可以通过将条件更改为if(@$sxml->validate()) {
来抑制这些错误,但是我没有得到所需的错误。
$sxml = new DOMDocument;
$sxml->preserveWhiteSpace = false;
$sxml->formatOutput = true;
$sxml->Load($file . '.xml');
if($sxml->validate()) {
//doesn't matter it's valid
} else {
libxml_use_internal_errors(true);
$errors = libxml_get_errors();
if(!empty($errors)) {
foreach($errors as $error) {
echo $error . '<br />';
}
}
libxml_clear_errors();
}
这给了我
Warning: DOMDocument::validate(): Element test content does not follow the DTD, expecting (this) got (that) Warning: DOMDocument::validate(): Element test content does not follow the DTD, expecting (this) got (that)Warning: DOMDocument::validate(): Element test content does not follow the DTD, expecting (this) got (that)Warning: DOMDocument::validate(): Element test content does not follow the DTD, expecting (this) got (that)
有没有办法遍历每个错误并分别输出呢?
else
中的任何内容都不会输出所有来自$sxml->validate()
调用的内容。例如
- Warning: DOMDocument::validate(): Element test content does not follow the DTD, expecting (this) got (that)
- Warning: DOMDocument::validate(): Element test content does not follow the DTD, expecting (this) got (that)
- Warning: DOMDocument::validate(): Element test content does not follow the DTD, expecting (this) got (that)
- Warning: DOMDocument::validate(): Element test content does not follow the DTD, expecting (this) got (that)
最佳答案
请参阅DOMDocument::validate
的PHP手册中schaffhirt的注释。它包含一个确实可以做到这一点的类:
<?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
}
?>
关于php - DomDocument验证错误格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32314363/