How does the hierarchy of parent and child elements work in PHP when using createElement and appendChild functions for XML generation?

When using createElement and appendChild functions in PHP for XML generation, the hierarchy of parent and child elements is established by first creating the parent element using createElement, then creating the child elements and appending them to the parent element using appendChild. This ensures that the child elements are nested within the parent element in the XML structure.

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

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

// Create and append child elements to the parent element
$childElement1 = $doc->createElement('child1', 'value1');
$parentElement->appendChild($childElement1);

$childElement2 = $doc->createElement('child2', 'value2');
$parentElement->appendChild($childElement2);

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