我有一个xml文件,我正在从中读取数据并尝试通过表单进行更新。我有一个书清单和一个“编辑”按钮,该按钮将书的ID传递到名为“ edit.php”的页面。 $ id变量已通过$ _GET正确传递(在测试页面上回显了$ id)。这是我尝试的方法,但是在下面的指示行中我仍然收到错误。这是我阅读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');
?>
我在这里处理提交表单:
<?php
if (isset($_POST['submit'])) {
$title->nodeValue = $_POST['newTitle'];
$author->nodeValue = $_POST['newAuthor'];
htmlentities($xml->save('DATA/Books.xml'));
}
?>
这是我的表格:
<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>
这是我的xml示例:
<?xml version="1.0" encoding="UTF-8"?>
<books>
<book id="3"><title>Test</title><author>Test</author></book>
</books>
答案 0 :(得分:0)
考虑构建所需的节点片段,然后将其导入主DOM。请参见下面的示例,您可以在其中将表单值调整到所需的位置:
$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();
https://docs.scrapy.org/en/latest/topics/request-response.html#scrapy.http.Request
输出
<?xml version="1.0" encoding="UTF-8"?>
<books>
<book>
<title>my new title</title>
<book>my new book</book>
</book>
</books>