Source: OneLogin PHP Toolkit
/**
* This function load an XML string in a safe way.
* Prevent XEE/XXE Attacks
*
* @param DOMDocument $dom The document where load the xml.
* @param string $xml The XML string to be loaded.
*
* @throws Exception
*
* @return DOMDocument $dom The result of load the XML at the DomDocument
*/
public static function loadXML($dom, $xml)
{
assert('$dom instanceof DOMDocument');
assert('is_string($xml)');
if (strpos($xml, '<!ENTITY') !== false) {
throw new Exception('Detected use of ENTITY in XML, disabled to prevent XXE/XEE attacks');
}
$oldEntityLoader = libxml_disable_entity_loader(true);
$res = $dom->loadXML($xml);
libxml_disable_entity_loader($oldEntityLoader);
if (!$res) {
return false;
} else {
return $dom;
}
}