当我print_r($nodes);
时,我得到:
Array (
[0] => SimpleXMLElement Object (
[kategoria_6] => 1
[opis_6] => 1
[img] => slides/slide0.jpg
)
[1] => SimpleXMLElement Object (
[kategoria_6] => 2
[opis_6] => 2
[img] => slides/slide1.jpg
)
[2] => SimpleXMLElement Object (
[kategoria_6] => 3
[opis_6] => 3
[img] => slides/slide4.jpg
)
[3] => SimpleXMLElement Object (
[kategoria_6] => 4
[opis_6] => 4
[img] => slides/slide3.jpg
)
[4] => SimpleXMLElement Object (
[kategoria_6] => 7
[opis_6] => 7
[img] => slides/slide2.jpg
)
)
现在在这种情况下,我不能这样做:
$nodes->asXML("c:\\aaa.xml");
因为这是一个我可以做的数据f.ex:
$nodes[1]->asXML("c:\\aaa.xml");
但我只会得到一个元素。我需要获得所有这个数组,或者更好地将其更改为:
SimpleXMLElement Object (
[item] => Array (
[0] => SimpleXMLElement Object (
[kategoria_6] => 1
[opis_6] => 1
[img] => slides/slide0.jpg
)
[1] => SimpleXMLElement Object (
[kategoria_6] => 2
[opis_6] => 2
[img] => slides/slide1.jpg
)
[2] => SimpleXMLElement Object (
[kategoria_6] => 3
[opis_6] => 3
[img] => slides/slide4.jpg
)
[3] => SimpleXMLElement Object (
[kategoria_6] => 4
[opis_6] => 4
[img] => slides/slide3.jpg
)
[4] => SimpleXMLElement Object (
[kategoria_6] => 7
[opis_6] => 7
[img] => slides/slide2.jpg
)
)
)
如何解决?
答案 0 :(得分:5)
不幸的是,SimpleXML本身并不容易让你做你想做的事情。幸运的是,DOM确实( FIXED ):
// Create a new DOMDocument
$dom = new DOMDocument('1.0', 'utf-8');
// Create the DocumentElement
$documentElement = $dom->appendChild($dom->createElement('objects'));
// Loop the SimpleXML elements and import them into DOM
foreach ($val as $element) {
$documentElement->appendChild($dom->importNode(dom_import_simplexml($element), TRUE));
}
// Save to file
$dom->save("c:\\aaa.xml");