PHP 5 can validate XML against three types of files: Document Type Definitions (DTDs), Schemas (.xsd), and relaxNG. For the latter two, the following four methods of the DOM object exist:
The preceding code uses relaxNGValidate() to validate a (well-formed) XML file against a nonmatching relaxNG file. If you change <element name="person"> to <element name="author"> in the file quotes.rng, the validation succeeds. Validating XML Against relaxNG (validate-rng.php)<?php $dom = new DOMDocument; $dom->load('quotes.xml'); echo 'Validation ' . (($dom->relaxNGValidate('quotes.rng')) ? 'succeeded.' : 'failed.'); ?>
Validating a Schema is similar and shown in the file validate-xsd.php in the download repository. When it comes to validating DTDs, you have to patch the XML a bit. The DTD file must be included in the file or referenced like this: <!DOCTYPE note SYSTEM "quotes.dtd"> Then, just load the XML document into a DOM object and call validate(). The following contains the appropriate code; the file referenced in the code repository contains an intentional error in the DTD (month instead of year). Validating XML Against a DTD (validate-dtd.php)<?php $dom = new DOMDocument(); $dom->load('quotes-dtd.xml'); echo 'Validation ' . (($dom->validate()) ? 'succeeded.' : 'failed.'); ?>
|