Marcello Impastato
Marcello Impastato

Reputation: 2281

How to get number of nodes inside a xml file?

Having a xml file so formed:

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

How i can count nodes inside ... ? In example above, the function should be turn 3 as result becouse present three nodes.

NOTE: I access to ... so:

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

Upvotes: 1

Views: 37

Answers (2)

Chandana Kumara
Chandana Kumara

Reputation: 2645

You can do as:

Refer: https://www.php.net/manual/en/book.dom.php

$dom->getElementsByTagName('chapter')->length;

Unless you can use this:

$xpath->evaluate('count(//book/chapter');

Upvotes: 1

Rakesh Sojitra
Rakesh Sojitra

Reputation: 3658

Try this code

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']);

EDIT

Using DOMXpath try this

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

Upvotes: 0

Related Questions