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

时间:2011-09-29 22:48:27

标签: php xml domdocument

对于熟悉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-&gt; appendChild($ x)附加到我的文档中;

我想创建上面的结构并返回可以附加在DOMDocument

中的对象

1 个答案:

答案 0 :(得分:0)

以下代码:

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