且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用比DOM更深层的PHP DOM向XML添加新元素?

更新时间:2023-11-07 12:42:16


将内容添加到文件根目录下的XML文件,但我真的需要做的比这更深刻。


你不会在任何地方添加内容时刻!您创建带有文本的< title>和< link>元素节点,那么您对它们什么都不做。您应该将它们传递到< item>元素节点上的'appendChild'(您也正在创建它并立即将其分配给变量)。



这是一个起点:

  $ screenshots = $ dom-> getElementsByTagName(screenshots)[0]; 

$ title = $ dom-> createElement(title);
$ title-> appendChild($ dom-> createTextNode($ newshottitle));
$ item = $ dom-> createElement(item);
$ item-> appendChild($ title);
$ screenshots-> appendChild($ item);


All of the examples I can find online about this involve simply adding content to an XML file at the document root, but I really need to do it deeper than that.

My XML file is simple, I have:

<?xml v1 etc>
<channel>
<screenshots>
<item>
  <title>Image Title</title>
  <link>www.link.com/image.jpg</link>
</item>
</screenshots>
</channel>

All I want to be able to do is add new "item" elements, each with a title and link. I know I need to be using PHP DOM, but I'm stumped as to how to code it so that it adds data within "screenshots" rather than overwriting the whole document. I have a suspicion I may need to use XPath too, but I have no idea how!

The code I have pieced together from online examples looks like this (but I'm certain it's wrong)

$newshottitle = "My new screenshot";
$newshotlink = "http://www.image.com/image.jpg";

$dom = newDomDocument;
$dom->formatOutput = true;
$dom->load("../xml/screenshots.xml");

$dom->getElementsByTagName("screenshots");
$t = $dom->createElement("item");
$t = $dom->createElement("title");
$t->appendChild($dom->createTextNode("$newshottitle"));

$l = $dom->createElement("link");
$l->appendChild($dom->createTextNode("$newshotlink"));

$dom->save("../xml/screenshots.xml");

adding content to an XML file at the document root, but I really need to do it deeper than that.

You're not adding content anywhere at the moment! You create <title> and <link> element nodes with text in, then you do nothing with them. You should be passing them into ‘appendChild’ on the <item> element node (which also you are currently creating and immediately throwing away by not assigning it to a variable).

Here's a starting-point:

$screenshots= $dom->getElementsByTagName("screenshots")[0];

$title= $dom->createElement("title");
$title->appendChild($dom->createTextNode($newshottitle));
$item= $dom->createElement("item");
$item->appendChild($title);
$screenshots->appendChild($item);