<!--PHP編程實(shí)戰(zhàn)-->
<!--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"
),
);
//從根節(jié)點(diǎn)開(kāi)始生成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'));
?>
知識(shí)點(diǎn)
- 使用 new SimpleXMLElement('<animals/>');創(chuàng)建了一個(gè)新的SimpleXMLElement元素.為了自頂層元素向下依次填充文檔,通過(guò)調(diào)用addChild來(lái)創(chuàng)建子元素,并將一個(gè)引用存儲(chǔ)到新建的元素.
- 通過(guò)元素的引用,就可以添加子元素.重復(fù)這個(gè)過(guò)程,可以生成一個(gè)完整的節(jié)點(diǎn)樹(shù).
- 輸出函數(shù)asXML不能很好地格式化輸出.
- 使用DOMDocument類可以很好第輸出XML.
- 節(jié)點(diǎn)要先引入再添加.