How can PHP be used to check for and ensure proper closing of HTML tags like <a>?

To check for and ensure proper closing of HTML tags like <a>, you can use PHP to parse the HTML content and check if each opening tag has a corresponding closing tag. This can be done by using PHP's DOMDocument class to load the HTML content, traverse through the DOM tree, and check for any unclosed tags. If an unclosed tag is found, you can programmatically close it to ensure proper HTML structure.

$html = &#039;&lt;a href=&quot;#&quot;&gt;Link&lt;/a&gt;&lt;div&gt;&lt;p&gt;Paragraph&lt;/p&gt;&lt;/div&gt;&#039;;
$doc = new DOMDocument();
$doc-&gt;loadHTML($html);

$open_tags = [];
$unclosed_tags = [];

foreach ($doc-&gt;getElementsByTagName(&#039;*&#039;) as $element) {
    if ($element-&gt;nodeType === XML_ELEMENT_NODE) {
        if ($element-&gt;hasChildNodes()) {
            array_push($open_tags, $element-&gt;tagName);
        } else {
            if (!in_array($element-&gt;tagName, $open_tags)) {
                array_push($unclosed_tags, $element-&gt;tagName);
            } else {
                array_pop($open_tags);
            }
        }
    }
}

foreach ($unclosed_tags as $tag) {
    $html .= &#039;&lt;/&#039; . $tag . &#039;&gt;&#039;;
}

echo $html;