0

XMLファイルに書き込もうとしていますが、構文がわかりません。しかし、XMLファイルを開くことはできます。これまでの私のコードは次のとおりです。

<?php
$doc = new DOMDocument();
$doc->load("xml/latestContent.xml");
$latestpic = $doc->getElementsByTagName("latestpic");
?>

以前の方法を使用しましたが、これはもう使用したくないSIMPLEXMLを使用しています。

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

HTH

于 2012-05-17T14:28:57.643 に答える