Count Elements in XML using PHP

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • doc1355
    New Member
    • Sep 2007
    • 16

    Count Elements in XML using PHP

    I have a XML file that is automaticaly generated from a database. It contains variable numbers of <product>.... .</product> element.
    How can I count number of "<product>..... </product>" elements in php?

    Thanks
  • Dormilich
    Recognized Expert Expert
    • Aug 2008
    • 8694

    #2
    that depends on which php version you are using. with php5 there might be a hint in the DomDocument definition on www.php.net, this could reduce it to something like getElementsByTa gName().length (javascript).

    Nevertheless, there is a count() function in XSL:
    [CODE=xsl]<xsl:value-of select="count(//product)" />[/CODE]
    would output the number of all <product> elements. You can certainly process such a stylesheet with php and you get your count number.

    regards

    Comment

    • Atli
      Recognized Expert Expert
      • Nov 2006
      • 5062

      #3
      You could of course always try to use a regular expression. The preg_match_all function will search for a given pattern and return the number of matches it finds.

      Comment

      • ak1dnar
        Recognized Expert Top Contributor
        • Jan 2007
        • 1584

        #4
        I think there is a easy way for you. Have you ever tried DOMDocument

        [PHP]$xml= "products.x ml";
        $xmlDoc = new DOMDocument();
        $xmlDoc->load($xml);
        $product = $xmlDoc->getElementsByT agName("product ");
        $numOfproducts = $product->length;
        echo $numOfproducts;[/PHP]

        This will print the output as 3 for your xml file in In this thread :D

        Good luck!

        Comment

        Working...