How can DOM object methods be utilized to manipulate XML files in PHP for better control and accuracy?

When working with XML files in PHP, DOM object methods can be utilized to manipulate the XML structure, making it easier to navigate and modify specific elements or attributes. By using DOM methods such as createElement(), appendChild(), and setAttribute(), you can accurately control the content and structure of the XML file.

// Load the XML file
$xml = new DOMDocument();
$xml->load('data.xml');

// Create a new element
$newElement = $xml->createElement('newElement');
$newElement->setAttribute('attribute', 'value');

// Append the new element to the document
$xml->documentElement->appendChild($newElement);

// Save the modified XML back to the file
$xml->save('data.xml');