Jdiid
Jdiid

Reputation: 45

count number of items in xml with php

I have to parse xml files that look like this : http://goo.gl/QQirq

How can I count number of items/records in this xml- by 'item' I mean a 'productItem' element, ie there are 5 items in the example xml. I don't specify the tag name 'productItem' when parsing the xml, so I can't count occurrences of 'productItem'. Here is the code I have:

        <?php
$doc = new DOMDocument();
$doc->load("test.xml");
$xpath = new DOMXpath( $doc );
$nodes = $xpath->query( '//*| //@*' );
$nodeNames = array();
foreach( $nodes as $node )
{
    $nodeNames = $node->nodeName;
    $name=$node->nodeName;
    $value=$node->nodeValue;
    echo ''.$name.':'.$value.'<br>';
    }

?> 

How can I count number of items and display them one by one, like this ideally : http://goo.gl/O1FI8 ?

Upvotes: 1

Views: 3385

Answers (1)

artragis
artragis

Reputation: 3713

Why don't you use DOMDocument::getElementsByTagName?

//get the number of product items
echo $doc->getElementsByTagName('productitem')->length;
 //traverse the collection of productitem
foreach($doc->getElementsByTagName('productitem') as $element){
  //$element is a DOMElement
  $nodeNames = $element->nodeName;
  $name=$element->nodeName;
  $value=$element->nodeValue;
  echo ''.$name.':'.$value.'<br>';
}

As you want to traverse your document, use XPath is just greedy. Moreover you will instantiate each node of the document even if you only want one or two.

You can use hasChildNodes methode and childNodes attribute to traverse your document

function searchInNode(DOMNode $node){

     if(isGoodNode($node)){//if your node is good according to your database
         mapTheNode($node);
     }
     if($node->hasChildNodes()){
         foreach($node->childNodes as $nodes){
             searchInNode($nodes);
         }
     }
}
searchInNode($domdocument);    

Upvotes: 1

Related Questions