Connecting Tech Pros Worldwide Forums | Help | Site Map

Count Elements in XML using PHP

Newbie
 
Join Date: Sep 2007
Location: USA
Posts: 16
#1: Aug 28 '08
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's Avatar
Moderator
 
Join Date: Aug 2008
Location: Leipzig, Germany
Posts: 4,300
#2: Aug 28 '08

re: Count Elements in XML using PHP


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 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.

regards
Atli's Avatar
Moderator
 
Join Date: Nov 2006
Location: Iceland
Posts: 3,997
#3: Aug 28 '08

re: Count Elements in XML using PHP


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.
ak1dnar's Avatar
Moderator
 
Join Date: Jan 2007
Location: Colombo
Posts: 1,441
#4: Aug 29 '08

re: Count Elements in XML using PHP


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

[PHP]$xml= "products.xml";
$xmlDoc = new DOMDocument();
$xmlDoc->load($xml);
$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!
Reply