我有一个 xml 文档如下:
<?xml version="1.0" encoding="UTF-8" ?>
<books>
<book>
<name>Title One</name>
<year>2014</year>
<authors>
<author>
<name>Author One</name>
</author>
</authors>
</book>
<book serie="yes">
<name>Title Two</name>
<year>2015</year>
<authors>
<author>
<name>Author two</name>
</author>
<author>
<name>Author three</name>
</author>
</authors>
</book>
<book serie="no">
<name>Title Three</name>
<year>2015</year>
<authors>
<author>
<name>Author four</name>
</author>
</authors>
</book>
</books>
我想将它转换成下面的数组。
array(
array('Tittle one', 2014, 'Author One'),
array('Tittle two', 2015, 'Author two, Author three'),
array('Tittle three', 2015, 'Author four'),
);
我下面的代码无法生成我想要的数组结构:
function arrayRepresentation(){
$xmldoc = new DOMDocument();
$xmldoc->load("data/data.xml");
$parentArray = array();
foreach ($xmldoc->getElementsByTagName('book') as $item) {
$parentArray[] = array_generate($item);
}
var_dump($parentArray);
}
function array_generate($item){
$movieArray = array();
$childMovieArray = array();
for ($i = 0; $i < $item->childNodes->length; ++$i) {
$child = $item->childNodes->item($i);
if ($child->nodeType == XML_ELEMENT_NODE) {
if(hasChild($child)){
$childMovieArray = array_generate($child);
}
}
$movieArray[] = trim($child->nodeValue);
}
if(!empty($childMovieArray)){
$movieArray = array_merge($movieArray,$childMovieArray);
}
return $movieArray;
}
基本上我循环遍历节点来获取 xml 元素值。然后我检查我的节点是否有更多的子节点,如果有,我再次循环它以获取值。我无法推断出一种方法:(i)不会给我一些空数组元素(ii)检查任何子节点并将所有 xml 同级元素放入单个字符串中
慕码人2483693