Skip to content

Instantly share code, notes, and snippets.

@ydegtyar
Created May 30, 2018 09:43
Show Gist options
  • Save ydegtyar/960264624e4138059b338a1af33c68bd to your computer and use it in GitHub Desktop.
Save ydegtyar/960264624e4138059b338a1af33c68bd to your computer and use it in GitHub Desktop.
Create DomElement from html string in PHP. You need to use DomDocument and than extract your element.
/**
@param string $html
@return \DomElement
*/
function getDomElementFromHtml($html)
{
$document = new \DOMDocument();
$document->loadHTML($html);
return $document->getElementsByTagName('*')->item(0);
}
$html = '<a href="https://example.com">Example.com</a>';
$linkDomElement = getDomElementFromHtml($html);
echo $linkDomElement->textContent; // Example.com
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment