How can DOMDocument or Simple XML be used to access and manipulate XML files in PHP?

To access and manipulate XML files in PHP, you can use either the DOMDocument or SimpleXML classes. DOMDocument provides a way to create, parse, and manipulate XML documents, while SimpleXML offers a simpler and more concise way to work with XML data. Both classes allow you to load XML files, traverse the XML structure, modify elements and attributes, and save the changes back to the file.

// Using DOMDocument to access and manipulate XML file
$doc = new DOMDocument();
$doc->load('data.xml');

$root = $doc->documentElement;
$books = $root->getElementsByTagName('book');

foreach ($books as $book) {
    $title = $book->getElementsByTagName('title')->item(0)->nodeValue;
    $newTitle = $doc->createElement('title', 'New Title');
    $book->replaceChild($newTitle, $book->getElementsByTagName('title')->item(0));
}

$doc->save('data.xml');