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:
x
9
1
$custom_font = '<link href="https://fonts.googleapis.com/css2?family=Poppins:wght@400;700&display=swap" rel="stylesheet">';
2
3
$link = $custom_font;
4
libxml_use_internal_errors(true);
5
$dom = new DOMDocument();
6
$dom->loadHTML($link);
7
foreach ($dom->getElementsByTagName("link") as $a) {
8
echo $a->getAttribute("href");
9
}
- Link to Repl.it
- PHP: DOMDocument