How can DOMDocument be used to create nested lists in PHP?
To create nested lists using DOMDocument in PHP, you can first create a new DOMDocument object, then create the outer list element (ul or ol), and append it to the document. Next, create the inner list elements (li) and append them to the outer list element to create the nested structure. Finally, output the generated HTML using the saveHTML() method of the DOMDocument object.
<?php
// Create a new DOMDocument object
$doc = new DOMDocument();
// Create the outer list element
$outerList = $doc->createElement('ul');
$doc->appendChild($outerList);
// Create and append inner list elements
$innerList1 = $doc->createElement('li', 'Item 1');
$outerList->appendChild($innerList1);
$innerList2 = $doc->createElement('li', 'Item 2');
$outerList->appendChild($innerList2);
// Create a nested list
$nestedList = $doc->createElement('ul');
$innerList2->appendChild($nestedList);
$nestedItem1 = $doc->createElement('li', 'Nested Item 1');
$nestedList->appendChild($nestedItem1);
$nestedItem2 = $doc->createElement('li', 'Nested Item 2');
$nestedList->appendChild($nestedItem2);
// Output the generated HTML
echo $doc->saveHTML();
?>
Keywords
Related Questions
- What are the advantages of using switch case statements over if-else conditions when handling multiple $_GET parameters in PHP scripts?
- What is the best method in PHP to check if specific elements contain values within an XML container?
- How can one avoid variable conflicts when including PHP files with similar SQL queries?