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);
}
}
}
?>
DOMDocument::validate
(PHP 5)
DOMDocument::validate — Valida el documento basado en su DTD
Descripción
bool DOMDocument::validate
( void
)
Valida el documento basado en su DTD.
También se puede usar la propiedad validateOnParse de DOMDocument para realizar la validación de DTD.
Valores devueltos
Devuelve TRUE en caso de éxito o FALSE en caso de error.
Si el documento no tiene el DTD adjunto, este método devolverá FALSE.
Ejemplos
Ejemplo #1 Ejemplo de validación de DTD
<?php
$dom = new DOMDocument;
$dom->Load('book.xml');
if ($dom->validate()) {
echo "¡Este documento es válido!\n";
}
?>
También se puede validar un fichero XML mientras se carga:
<?php
$dom = new DOMDocument;
$dom->validateOnParse = true;
$dom->Load('book.xml');
?>
Ver también
- DOMDocument::schemaValidate() - Valida un documento basado en un esquema
- DOMDocument::schemaValidateSource() - Valida un documento basado en un esquema
- DOMDocument::relaxNGValidate() - Realiza una validación relaxNG del documento
- DOMDocument::relaxNGValidateSource() - Realiza una validación relaxNG del documento
cabral dot brc at gmail dot com ¶
2 years ago
a dot schaffhirt at sedna-soft dot de ¶
4 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
darren at viamedia dot co dot za ¶
4 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();
?>
