Manipulate HTML tags with DOMDocument

    private function main_menu(){
        $menu = menu('Main');

        $dom = new \DOMDocument;
        $dom->loadHTML($menu);
        //echo $dom->saveHTML();
        //exit();

        $output = '<ul class="list-reset navbar-nav">';

        $xpath = new \DOMXPath($dom);
        $nodes = $xpath->query("//li");
        foreach($nodes as $node) {
            //Get child node
            $a = $node->getElementsByTagName('a')->item(0);

            //If li has active class
            $a->setAttribute('class', 'navbar-item');
            if($node->hasAttributes() == true){
                foreach($node->attributes as $attr){
                    if($attr->nodeName == 'class' && $attr->nodeValue == 'active'){
                        $a->setAttribute('class', 'navbar-item active');
                    }
                }
            }

            //Remove active class of li
            $node->setAttribute('class', '');

            $output .= $dom->saveHTML($node);
        }
        //echo $dom->saveHTML($node);
        //exit();

        $output .= '</ul>';
        //logg($output);
        return $output;
    }

Reference:

  1. https://www.awaimai.com/2113.html
  2. https://stackoverflow.com/questions/16127142/modify-html-attribute-with-php
  3. https://stackoverflow.com/questions/2385834/php-dom-get-all-attributes-of-a-node