我正在尝试写入我的XML文件但不确定语法!我可以打开XML文件。到目前为止,这是我的代码:
<?php
$doc = new DOMDocument();
$doc->load("xml/latestContent.xml");
$latestpic = $doc->getElementsByTagName("latestpic");
?>
我使用过以前的方法,但这是使用SIMPLE XML,我不想再使用它了:
<?php
$xml = simplexml_load_file("xml/latestContent.xml");
$sxe = new SimpleXMLElement($xml->asXML());
$latestpic = $sxe->addChild("latestpic");
$latestpic->addChild("item", "Latest Pic");
$latestpic->addChild("content", $latestPic);
$latestvid = $sxe->addChild("latestvideo");
$latestvid->addChild("item", "Latest Video");
$latestvid->addChild("content", $videoData);
$latestfact = $sxe->addChild("latestfact");
$latestfact->addChild("item", "Latest Fact");
$latestfact->addChild("content", $factData);
$sxe->asXML("xml/latestContent.xml");
?>
如何让我的DOM与SIMPLE方法做同样的事情?
提前谢谢!
答案 0 :(得分:1)
我根据你的SimpleXML代码做什么来推断你的latestContent.xml文件是什么样的。为了使您的当前代码有意义,在SimpleXML代码修改之前,latestContent.xml可能看起来像:
<?xml version="1.0" ?>
<root />
您使用DOMDocument在SimpleXML中编写的等效代码将如下所示:
<?php
// Load XML
$doc = new DOMDocument();
$doc->load("xml/latestContent.xml");
// Get root element
$rootElement = $doc->documentElement;
// Create latestpic element as a child of the root element
$latestPicElement = $rootElement->appendChild($doc->createElement("latestpic"));
$latestPicElement->appendChild($doc->createElement("item", "Latest Pic"));
$latestPicElement->appendChild($doc->createElement("content", $latestPic));
// Create latestvideo element as a child of the root element
$latestVidElement = $rootElement->appendChild($doc->createElement("latestvideo"));
$latestVidElement->appendChild($doc->createElement("item", "Latest Video"));
$latestVidElement->appendChild($doc->createElement("content", $videoData));
// Create latestfact element as a child of the root element
$latestFactElement = $rootElement->appendChild($doc->createElement("latestfact"));
$latestFactElement->appendChild($doc->createElement("item", "Latest Fact"));
$latestFactElement->appendChild($doc->createElement("content", $factData));
// Save back to XML file
$doc->save("xml/latestContent.xml");
?>
HTH