How to validate xml file w/o DTD

php

Solution

Here are two levels of validation for a XML file. The first one is the XML syntax itself. A XML document that conforms to that rules is called "wellformed". You do this validation by loading the XML.

libxml_use_internal_errors(TRUE);
$dom = new DOMDocument();
$dom->load($file);
var_dump(libxml_get_errors());

Depending on your general error handling this can get more advanced. Be aware that here can be warnings and notices, too. DOMDocument has some automatic corrections.

The second level is the validation against specific rules for your XML format. This validation is only possible if you define the rules using a DTD, Schema oder RelaxNG.

Problem

I have an XML file to manipulate and am using a XSLT for processing. I want to validate the XML file initially before the XSLT transform. This is my code : ``` <?php $doc = new DOMDocument(); $doc->load('somefile.xml'); $isValid = $doc->validate(); if(!$isValid) { echo "$doc is INVALID!"; }else{ $xsldoc = new DOMDocument(); $xsldoc->load('somename.xslt'); $xslt = new XSLTProcessor(); $xslt->importStylesheet($xsldoc); $result = $xslt->transformToDoc($doc); $result->save('somefile.xml'); } ?> ``` But after running this php file I get following errors: ``` Warning: DOMDocument::validate(): no DTD found! in C:\test.php on line 10 Catchable fatal error: Object of class DOMDocument could not be converted to string in C:\test.php on line 13 ``` Wherein I don't have any DTD file to validate against, So how I can validate now? Thanks!

Original source