使用 DOM 文档将数据附加到 xml 文件


Appending data to xml file with DOM document

我正在尝试将新数据附加到现有的xml文件中。这是我到目前为止所拥有的:

 $doc = new DOMDocument();
 $doc->formatOutput = true;
 $doc->loadXml('library.xml');
 $path = new DOMXPath($doc);
 $b=$doc->createElement('book');
 $ISBN = $doc->createElement( 'isbn' );
 $ISBN->appendChild(
  $doc->createTextNode( $_GET['isbn'] )
  );
  $b->appendChild( $ISBN );

  $edition = $doc->createElement( 'edition' );
  $edition->appendChild(
  $doc->createTextNode( $_GET['ed'] )
      );
  $b->appendChild( $edition );*/

  $doc->save("library.xml");

我在如何到达要插入数据的位置时遇到问题。我看到一些使用查询()或这个:

$query = sprintf('//record[./title[contains(., "%s")]]', $searchString);

但我想知道是否有人可以解释路径是如何编写的。

//record[./title[contains(., "%s")]]

是一个 XPath 查询,它意味着在 XML 中查找具有包含
搜索字符串

您需要获取对所需节点的引用,然后将 Child 附加到该节点。您似乎没有附加到现有节点的任何位置

在这里看看如何到达你想要附加的位置http://php.net/manual/en/domxpath.query.php