2016-11-10 227 views
1

拥有如此形成的xml文件:如何获取xml文件中的节点数量?

<book id="1"> 
    <chapter id="1"> 
    ... 
    </chapter> 
    <chapter id="2"> 
    ... 
    </chapter> 
    <chapter id="3"> 
    ... 
    </chapter> 
</book> 

我怎么能指望内部节点...? 在上面的例子中,函数应该变为3,因为结果是三个节点。

注: 我访问...所以:

$xpath = new DOMXPath($filename); 
$book = $xpath->query("//book[@id='1']")->item(0); 
+0

你尝试使用'xpath'或'xquery'? – Jagrut

+0

我使用domxpath。 –

+0

@MarcelloImpastato:请检查我编辑的答案 –

回答

0

试试这个代码

function xml2array($xmlObject, $out = array()) { 
    foreach ((array) $xmlObject as $index => $node) 
     $out[$index] = (is_object($node)) ? xml2array($node) : $node; 

    return $out; 
} 

$a = '<book> 
<chapter id = "1"> 
... 
</chapter> 
<chapter id = "2"> 
... 
</chapter> 
<chapter id = "3"> 
... 
</chapter> 
</book>'; 
$a = simplexml_load_string($a); 
$array=xml2array($a); 
echo count($array['chapter']); 

编辑

使用DOMXpath试试这个

echo $book = $xpath->query("//book[@id='1']/chapter")->length;