Skip to content

Instantly share code, notes, and snippets.

@mtvbrianking
Created July 3, 2018 18:52
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 mtvbrianking/e492bf5ef769d597bd1f98582f468122 to your computer and use it in GitHub Desktop.
Save mtvbrianking/e492bf5ef769d597bd1f98582f468122 to your computer and use it in GitHub Desktop.
Validate XML against XSD - Using XML Reader
<?php
/**
* Class XmlDomReader
*/
class XMLDomReader
{
/**
* XML Reader
* @var string
*/
protected $reader = '';
/**
* XmlValidator constructor.
*/
public function __construct()
{
libxml_use_internal_errors(true);
$this->reader = new \XMLReader();
}
/**
* Validate XML string
* @param $xml
* @return array
*/
public function validate($xml, $xsd)
{
$errors = array();
$this->reader->xml($xml);
$this->reader->setSchema($xsd);
while($this->reader->read()) {
if (!$this->reader->isValid()) {
foreach (libxml_get_errors() as $error) {
array_push($errors, [
'code' => $error->code,
'message' => $error->message,
]);
}
libxml_clear_errors();
break;
}
};
return $errors;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment