Are there any best practices or alternative approaches to handling self-closing tags in PHP when converting HTML to JSON?

When converting HTML to JSON in PHP, self-closing tags like <img> or <input> can cause issues as they are not valid JSON. One approach to handle this is to convert self-closing tags to their equivalent opening and closing tag format before converting to JSON. This can be achieved by using regular expressions to match self-closing tags and replace them with their equivalent opening and closing tags.

$html = &#039;&lt;input type=&quot;text&quot; name=&quot;username&quot; /&gt;&#039;;
$json = json_encode(convertSelfClosingTags($html));

function convertSelfClosingTags($html) {
    // Regex pattern to match self-closing tags
    $pattern = &#039;/&lt;(\w+)([^&gt;]*)\/&gt;/&#039;;
    
    // Replace self-closing tags with opening and closing tags
    $html = preg_replace_callback($pattern, function($matches) {
        return &#039;&lt;&#039; . $matches[1] . $matches[2] . &#039;&gt;&lt;/&#039; . $matches[1] . &#039;&gt;&#039;;
    }, $html);
    
    return $html;
}