Last active
July 20, 2020 21:32
-
-
Save nickistre/d6386510586ef24d266082e8dd6ee2dc to your computer and use it in GitHub Desktop.
PHPUnit snippet for checking if a string is valid HTML using DOMDocument at a basic level.
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
protected function checkHTML($body) | |
{ | |
libxml_use_internal_errors(true); | |
$dom = new \DOMDocument(); | |
$dom->loadHTML($body, LIBXML_HTML_NOIMPLIED + LIBXML_HTML_NODEFDTD); | |
// Check for no errors | |
$this->assertCount(0, libxml_get_errors()); | |
// Check for doctype | |
$this->assertInstanceOf(\DOMDocumentType::class, $dom->childNodes[0]); | |
// Check for html, head, and body nodes | |
$xpath = new \DOMXPath($dom); | |
$this->assertCount(1, $xpath->query('/html'), 'No <html> node'); | |
$this->assertCount(1, $xpath->query('/html/head'), 'No valid <head> node'); | |
$this->assertCount(1, $xpath->query('/html/body'), 'No valid <body> node'); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment