0

我正在尝试写入我的 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 方法相同的事情?

4

1 回答 1

1

我正在根据您的 SimpleXML 代码正在执行的操作来推断您的 latestContent.xml 文件的外观。为了使您当前的代码有意义,latestContent.xml在被 SimpleXML 代码修改之前可能看起来像这样:

<?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");
?>

高温高压

于 2012-05-17T14:28:57.643 回答