By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
438,350 Members | 1,309 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 438,350 IT Pros & Developers. It's quick & easy.

Count Elements in XML using PHP

P: 16
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?

Aug 28 '08 #1
Share this Question
Share on Google+
3 Replies

Expert Mod 5K+
P: 8,639
that depends on which php version you are using. with php5 there might be a hint in the DomDocument definition on, this could reduce it to something like getElementsByTagName().length (javascript).

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

Aug 28 '08 #2

Expert 5K+
P: 5,058
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.
Aug 28 '08 #3

Expert 100+
P: 1,584
I think there is a easy way for you. Have you ever tried DOMDocument

[PHP]$xml= "products.xml";
$xmlDoc = new DOMDocument();
$product = $xmlDoc->getElementsByTagName("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!
Aug 29 '08 #4

Post your reply

Sign in to post your reply or Sign up for a free account.