php count xml elements

With DOM you can either use

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

to count all OfferName elements only. length is an attribute of DOMNodeList.

To count all OfferName elements within an OfferNameList, you can use DOMXPath::evaluate

$xpath->evaluate('count(//OfferNameList/OfferName');

Note that within is somewhat inaccurate here as the XPath query will only consider direct children. Please adjust your question if you need OfferName elements anywhere below a OfferNameList element.

Also note that // will query anywhere in the document, which might be less efficient for large documents. If you know OfferNameList elements occur at a certain position in your XML only, use a direct path.


Full working example (run on codepad):

$xml = <<< XML
<root>
    <NotOfferNameList>
      <OfferName>...</OfferName>
      <OfferName>...</OfferName>
      <OfferName>...</OfferName>
    </NotOfferNameList>
    <OfferNameList>
      <OfferName>...</OfferName>
      <OfferName>...</OfferName>
      <OfferName>...</OfferName>
    </OfferNameList>;
</root>
XML;

$dom = new DOMDocument;
$dom->loadXml($xml);

// count all OfferName elements
echo $dom->getElementsByTagName('OfferName')->length, PHP_EOL; // 6

// count all OfferNameList/OfferName elements
$xp = new DOMXPath($dom);
echo $xp->evaluate('count(//OfferNameList/OfferName)'); // 3

Leave a Comment