What are some common pitfalls when attempting to create nested lists in PHP with DOMDocument?

One common pitfall when creating nested lists in PHP with DOMDocument is not properly appending child elements to their parent elements. To solve this issue, make sure to create the parent element first, then create the child elements and append them to the parent element.

// Create a new DOMDocument
$doc = new DOMDocument();

// Create the parent ul element
$ul = $doc->createElement('ul');

// Append the ul element to the document
$doc->appendChild($ul);

// Create the first li element
$li1 = $doc->createElement('li', 'Item 1');
$ul->appendChild($li1);

// Create the second li element
$li2 = $doc->createElement('li', 'Item 2');
$ul->appendChild($li2);

// Create a nested ul element
$ulNested = $doc->createElement('ul');

// Append the nested ul element to the second li element
$li2->appendChild($ulNested);

// Create a nested li element
$liNested = $doc->createElement('li', 'Nested Item');
$ulNested->appendChild($liNested);

// Output the HTML
echo $doc->saveHTML();