Help | Site Map
Connecting Tech Pros Worldwide
Reply
 
LinkBack Thread Tools
  #1  
Old August 28th, 2008, 02:18 PM
Newbie
 
Join Date: Sep 2007
Location: USA
Posts: 16
Default 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
Reply
  #2  
Old August 28th, 2008, 03:08 PM
Dormilich's Avatar
Expert
 
Join Date: Aug 2008
Location: Leipzig, Germany
Age: 31
Posts: 646
Default

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
Reply
  #3  
Old August 28th, 2008, 06:05 PM
Atli's Avatar
Moderator
 
Join Date: Nov 2006
Location: Iceland
Age: 22
Posts: 2,777
Default

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.
Reply
  #4  
Old August 29th, 2008, 06:46 AM
ak1dnar's Avatar
Moderator
 
Join Date: Jan 2007
Posts: 1,400
Default

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
Reply

Bookmarks

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are Off
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On

What is Bytes?

We are a network of experts and professionals in IT and software development that help one another with answers to tough questions and share insights. Get the best answers to your questions from over network members.
Post your question now . . .
It's fast and it's free

Popular Articles