Created
July 3, 2018 18:52
-
-
Save mtvbrianking/e492bf5ef769d597bd1f98582f468122 to your computer and use it in GitHub Desktop.
Validate XML against XSD - Using XML Reader
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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