Skip to content
PHP Logo

How can one validate HTML markup in PHP to ensure proper functionality of anchors?

To validate HTML markup in PHP and ensure proper functionality of anchors, you can use the built-in DOMDocument class to parse the HTML and check for any anchor tags that are missing required attributes such as href. By iterating through the anchor tags and validating their attributes, you can ensure that all anchors have the necessary attributes for proper functionality.

php
$html = '<a href="https://example.com">Example Link</a>';

$dom = new DOMDocument();
$dom->loadHTML($html);

$anchors = $dom->getElementsByTagName('a');

foreach ($anchors as $anchor) {
    if (!$anchor->hasAttribute('href')) {
        echo 'Anchor tag is missing href attribute';
    }
}