Counting entries in XML file

Discussion in 'PHP' started by enchance, Oct 9, 2008.

  1. #1
    I loaded an XML file using simpelxml. Is there a way to count how many entries there are in that file?
    
    //my xml file
    <pets>
        <breed>Bulldog</breed>
        <breed>Terrier</breed>
        <breed>Chihuahua</breed>
    </pets>
    
    Code (markup):
    How do I get the number of entries in my XML file which in this case is 3? I hope to add more entries as the days go by.
     
    enchance, Oct 9, 2008 IP
  2. kmap

    kmap Well-Known Member

    Messages:
    2,215
    Likes Received:
    29
    Best Answers:
    2
    Trophy Points:
    135
    #2
    Try this
    <?
    $xml= "abc.xml"; //your xml filename
    $xmlDoc = new DOMDocument();
    $xmlDoc->load($xml);
    $product = $xmlDoc->getElementsByTagName("breed");
    $numOfproducts = $product->length;
    echo $numOfproducts;
    ?>

    Regards

    Alex
     
    kmap, Oct 9, 2008 IP
  3. enchance

    enchance Peon

    Messages:
    109
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #3
    I see. How do I access the values and attributes of each?
     
    enchance, Oct 9, 2008 IP
  4. juust

    juust Peon

    Messages:
    214
    Likes Received:
    11
    Best Answers:
    0
    Trophy Points:
    0
    #4
    if you only want to use simplexml:
    
    $c=0;
    foreach($xml->breed as $b) $c++;
    
    PHP:
    which returns $c=3

    or
    
    $c = count($xml->breed);
    
    PHP:
    which is zero-based and returns $c=2
     
    juust, Oct 9, 2008 IP
  5. enchance

    enchance Peon

    Messages:
    109
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #5
    Thanks juust! That really did it.
     
    enchance, Oct 10, 2008 IP