September 24, 2020

How to extract attributes from an HTML string in PHP (without using RegEx)

Say you have an <a>, <link> or other HTML element and you need to extract its href (or other) attribute. You can extract those values using DOMDocument quite easily:

$custom_font = '<link href="https://fonts.googleapis.com/css2?family=Poppins:wght@400;700&display=swap" rel="stylesheet">';

$link = $custom_font;
libxml_use_internal_errors(true);
$dom = new DOMDocument();
$dom->loadHTML($link);
foreach ($dom->getElementsByTagName("link") as $a) {
    echo $a->getAttribute("href");
}