<!--PHP编程实战-->
<!--XML -->
<!--14-16-->
<!--使用SimpleXML生成基本的XML文档-->
<?php
$dogs_array = array(
array("name" => "snoopy",
"color" => "brown",
"breed" => "beagle cross"
),
array("name" => "jade",
"color" => "black",
"breed" => "lab cross"
),
);
$cats_array = array(
array("name" => "teddy",
"color" => "brown",
"breed" => "tabby"
),
);
//从根节点开始生成xml
$animals = new SimpleXMLElement('<animals/>');
$cats_xml = $animals->addChild('cats');
$dogs_xml = $animals->addChild('dogs');
foreach ($cats_array as $c) {
$cat = $cats_xml->addChild('cat');
foreach ($c as $key => $value) {
$tmp = $cat->addChild($key);
$tmp->{0} = $value;
}
}
foreach ($dogs_array as $c) {
$dog = $dogs_xml->addChild('dog');
foreach ($c as $key => $value) {
$tmp = $dog->addChild($key);
$tmp->{0} = $value;
}
}
var_dump($animals);
$animals->asXML('animals.xml');
$animals_dom = new DOMDocument('1.0');
$animals_dom->preserveWhiteSpace = false;
$animals_dom->formatOutput = true;
//返回DOMElement
$animals_dom_xml = dom_import_simplexml($animals);
$animals_dom_xml = $animals_dom->importNode($animals_dom_xml, true);
$animals_dom_xml = $animals_dom->appendChild($animals_dom_xml);
$animals_dom->save('animals_formatted.xml');
print '<br/><br/>';
//
var_dump(simplexml_load_file('animals.xml'));
?>
知识点
- 使用 new SimpleXMLElement('<animals/>');创建了一个新的SimpleXMLElement元素.为了自顶层元素向下依次填充文档,通过调用addChild来创建子元素,并将一个引用存储到新建的元素.
- 通过元素的引用,就可以添加子元素.重复这个过程,可以生成一个完整的节点树.
- 输出函数asXML不能很好地格式化输出.
- 使用DOMDocument类可以很好第输出XML.
- 节点要先引入再添加.