I have a xml file from which I'm reading data and trying to update via a form. I have a list of books and a button "edit" which passes the id of the book to a page named "edit.php". The $id variable is passed correctly via $_GET (echo-ed the $id on the page for testing). Here is what I tried, but I keep receiving an error at the indicated line below. Here is where I read the xml:
$xml = new DOMDocument('1.0', 'utf-8');
$xml->load('DATA/Books.xml');
$id = $_GET['id'];
//Get item Element
$book = $xml->getElementsByTagName('book')->item($id);
//Load child elements
$title= $book->getElementsByTagName('title')->item(0); //error here
$author= $book->getElementsByTagName('author')->item(0);
//Replace old elements with new
$book->replaceChild($title, $title);
$book->replaceChild($author, $author);
header('location:Books.php');
?>
Here is where I'm treating the submit form:
<?php
if (isset($_POST['submit'])) {
$title->nodeValue = $_POST['newTitle'];
$author->nodeValue = $_POST['newAuthor'];
htmlentities($xml->save('DATA/Books.xml'));
}
?>
Here is my form:
<form class="form" method="post">
<input type="text" name="newTitle" id="title" value="<?php echo $title->nodeValue;?>" class="form-control">
<input type="text" name="newAuthor" id="author" value="<?php echo $author->nodeValue;?>"
<input type="submit" name="submit" class="btn btn-info btn-md" value="Update">
</form>
And this is a sample of my xml:
<?xml version="1.0" encoding="UTF-8"?>
<books>
<book id="3"><title>Test</title><author>Test</author></book>
</books>
Consider building needed node fragments and then import into main DOM. See below example where you can adjust form values to needed locations:
$xml = new DOMDocument('1.0', 'utf-8');
$xml->preserveWhiteSpace = false;
$xml->formatOutput = true;
$xml->loadXML('<?xml version="1.0" encoding="UTF-8"?>
<books>
<book id="3">
<title>Test</title>
<author>Test</author>
</book>
</books>');
// Search Needed Path
$id = 3;
$xpath = new DOMXpath($xml);
$nodelist = $xpath->query("/books/book[@id='$id']");
$old_book = $nodelist->item(0);
// Create Fragment
$root = new DomDocument;
$new_book = $root->createElement('book');
$new_book->appendChild($root->createElement('title', 'my new title'));
$new_book->appendChild($root->createElement('book', 'my new book'));
$root->appendChild($new_book);
// Import Fragment
$new_book = $xml->importNode($root->documentElement, true);
// Replace Old for New
$old_book->parentNode->replaceChild($new_book, $old_book);
echo $xml->saveXML();
Output
<?xml version="1.0" encoding="UTF-8"?>
<books>
<book>
<title>my new title</title>
<book>my new book</book>
</book>
</books>