How can the extracted HTML menus be formatted into XML with submenus using PHP?

To format extracted HTML menus into XML with submenus using PHP, you can iterate through the HTML menus and create nested XML elements for each submenu. This can be achieved by using PHP DOMDocument and DOMElement classes to create the XML structure. By parsing the HTML menus and organizing them into a hierarchical XML format, you can easily generate XML files with submenus.

// Sample HTML menu structure
$htmlMenu = '<ul>
                <li>Menu 1
                    <ul>
                        <li>Submenu 1</li>
                        <li>Submenu 2</li>
                    </ul>
                </li>
                <li>Menu 2</li>
            </ul>';

// Create a new XML document
$xml = new DOMDocument('1.0');
$xml->formatOutput = true;

// Create root element
$menu = $xml->createElement('menu');
$xml->appendChild($menu);

// Parse HTML menu and create XML structure
$dom = new DOMDocument();
$dom->loadHTML($htmlMenu);

$ul = $dom->getElementsByTagName('ul')->item(0);
parseMenu($ul, $menu);

// Function to parse HTML menu and create XML structure
function parseMenu($ul, $parent) {
    $items = $ul->getElementsByTagName('li');

    foreach ($items as $item) {
        $menuItem = $parent->appendChild(new DOMElement('menuItem', trim($item->nodeValue)));

        $subMenu = $item->getElementsByTagName('ul')->item(0);
        if ($subMenu) {
            $submenuNode = $menuItem->appendChild(new DOMElement('submenu'));
            parseMenu($subMenu, $submenuNode);
        }
    }
}

// Output the XML
echo $xml->saveXML();