从返回domnode的函数构建xml文档


Building an xml document from functions that return DOMNodes

对于熟悉PHP中的DOM*类的人来说,我的问题相当简单。基本上我有不同的类我想返回给我一些东西我可以在我的xml文档

中添加

下面的伪代码应该能更好地演示

Class ChildObject{ function exportToXML( return a DOMNode ? ) }
Class ContainerObject{ 
function exportToXML(){
    $domSomething = new DOM*SOMETHING*;
    foreach($children as $child) $domSomething->appendChild($child->exportToXML);
    return $domSomething ;
} 
}

Now i want to create the entire DOMDocument
$xml = new DOMDocument();
$root = $xml->createElement('root');
foreach($containers as $container) $root->appendChild($container->exportToXML());

我尝试发送DOMDocument对象作为引用,没有工作。我尝试创建DOMNodes,但没有工作得那么好....所以我正在寻找一个简单的答案:为了实现上述功能,我需要返回什么数据类型?

<?php
    $xml = new DOMDocument();
    $h = $xml->createElement('hello');
    $node1 = new DOMNode('aaa'); 
    $node1->appendChild(new DOMText('new text content'));
    //node1 is being returned by a function
    $node2 = new DOMNode('bbb');
    $node2->appendChild(new DOMText('new text content'));
    //node2 is being returned by some other function
    $h->appendChild($node1);//append to this element the returned node1
    $h->appendChild($node2);//append to this element the returned node2
    $xml->appendChild($h);//append to the document the root node
    $content = $xml->saveXML();
    file_put_contents('xml.xml', $content);//output to an xml file
?>

上面的代码应该做以下事情:

考虑我想构建以下xml

<hello>
 <node1>aaa</node1>
 <node2>bbb</node2>
</hello>

node1也可以是一个有多个子节点的节点,所以node1可以像这样:

<node1>
 <child1>text</child1>
 <child2>text</child2>
 <child3>
  <subchild1>text</subchild1>
 </child3>
</node1>

基本上当我调用exportToXML()应该返回的东西,调用它$x,我可以在我的文档中添加使用$xml->appendChild($x);

我想创建上述结构并返回可以在DOMDocument

中添加的对象。

以下代码:

<?php
$xml = new DOMDocument();
$h = $xml->appendChild($xml->createElement('hello'));
$node1 = $h->appendChild($xml->createElement('aaa'));
$node1->appendChild($xml->createTextNode('new text content'));
$node2 = $h->appendChild($xml->createElement('bbb'));
$node2->appendChild($xml->createTextNode('new text content'));
$xml->save("xml.xml");
?>

会产生:

<?xml version="1.0"?>
<hello>
    <aaa>new text content</aaa>
    <bbb>new text content</bbb>
</hello>

您的示例XML显示<node1>aaa</node1>,但我认为您的各种代码片段示例在编辑时不同步=)如果您需要输出,请尝试:

<?php
$xml = new DOMDocument();
$h = $xml->appendChild($xml->createElement('hello'));
$node1 = $h->appendChild($xml->createElement('node1'));
$node1->appendChild($xml->createTextNode('aaa'));
$node2 = $h->appendChild($xml->createElement('node2'));
$node2->appendChild($xml->createTextNode('bbb'));
$xml->save("xml.xml");
?>