Skip to content

Instantly share code, notes, and snippets.

@nickistre
Last active July 20, 2020 21:32
Show Gist options
  • Save nickistre/d6386510586ef24d266082e8dd6ee2dc to your computer and use it in GitHub Desktop.
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.
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