Skip to content

Instantly share code, notes, and snippets.

@iamaravi
Created May 4, 2015 06:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save iamaravi/9ee0396107399ea6235d to your computer and use it in GitHub Desktop.
Save iamaravi/9ee0396107399ea6235d to your computer and use it in GitHub Desktop.
XML validation using XSD source.
<?php
function libxml_display_error($error)
{
$return = "<br/>\n";
switch ($error->level) {
case LIBXML_ERR_WARNING:
$return .= "<b>Warning $error->code</b>: ";
break;
case LIBXML_ERR_ERROR:
$return .= "<b>Error $error->code</b>: ";
break;
case LIBXML_ERR_FATAL:
$return .= "<b>Fatal Error $error->code</b>: ";
break;
}
$return .= trim($error->message);
if ($error->file) {
$return .= " in <b>$error->file</b>";
}
$return .= " on line <b>$error->line</b>\n";
return $return;
}
function libxml_display_errors() {
$errors = libxml_get_errors();
foreach ($errors as $error) {
print libxml_display_error($error);
}
libxml_clear_errors();
}
################################## Done with Helper functions ######################
// Enable user error handling
libxml_use_internal_errors(true);
$xsdData = '<?xml version="1.0"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified">
<xs:element name="lures">
<xs:complexType>
<xs:sequence>
<xs:element name="lure">
<xs:complexType>
<xs:sequence>
<xs:element name="lureName" type="xs:string"/>
<xs:element name="lureCompany" type="xs:string"/>
<xs:element name="lureQuantity" type="xs:integer"/>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>';
$xmlData = '<lures>
<lure>
<lureName>Silver Spoon</lureName>
<lureCompany>Clark</lureCompany>
<lureQuantity>Seven</lureQuantity>
</lure>
</lures>';
$xml = new DOMDocument();
$xml->loadXML($xmlData);
if (!$xml->schemaValidateSource($xsdData)) {
print '<b>Errors Found!</b>';
libxml_display_errors();
}
else {
echo "validated<p/>";
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment