Vahid Najafi
Vahid Najafi

Reputation: 5263

php count xml elements isn't work fine when there is one element

I have a problem in counting xml elements. Let's see an example.

<products>
  <product>
    <id>1</id>
    <name>first</name>
    <url>test1</url>
  </product>
  <product>
    <id>2</id>
    <name>second</name>
    <url>test1</url>
  </product>
</products>

In php: For this example it counts fine:

count($array['products']['product']);
// This gives me 2

But when I have only one product:

<products>
  <product>
    <id>1</id>
    <name>first</name>
    <url>test1</url>
  </product>
</products>

Now in php:

count($array['products']['product']);
// This gives me 3 , number of sub elements of product (It must be 1)
//(because in this case we have one product and there is no sub array for counting,
//so instead of another product, features of product is counting)

Any idea?

UPDATE:

I can use count($array['products']); when there is only one product. That's ok. BUT, I check the xml in a loop. How should I know whether it has one product or not? At first I must can count the product.

Upvotes: 0

Views: 95

Answers (5)

michi
michi

Reputation: 6625

it's unclear how you transformed the XML into that array.

If you parse the XML directly with SimpleXml, count() will give accurate results:

$xml = simplexml_load_string($x); // assume XML in $x
echo $xml->product->count(); 

Upvotes: 1

Vahid Najafi
Vahid Najafi

Reputation: 5263

Finally I made a solution: I must check whether product is multidimensional array or not.

In first case:

Array
(
  [0] => Array
    ([id]=>1...)
  [1] => Array
    ([id]=>2...)
)

In Second case:

Array
(
  [id]=>1...
)

Now I wrote a function to check whether it's multidimensional array or not. If the array is not multidimensional, so the count is one!

public function isMultiArray($arr){
    foreach ($arr as $key) {
        if (is_array($key)) {
            return true;
        }
        else return false;
    }
}

Upvotes: 0

Professor Abronsius
Professor Abronsius

Reputation: 33823

You didn't explain how you are deriving the array initially butI assume via DOMDocument? In which case you should be able to deduce the length / count using a method like this.

$strxml='<products>
  <product>
    <id>1</id>
    <name>first</name>
    <url>test1</url>
  </product>
</products>';


$dom=new DOMDocument;
$dom->loadXML( $strxml );

$col=$dom->getElementsByTagName('product');
if( is_object( $col ) ){
    echo $col->length;  
}
$col=$dom=null;

Upvotes: 1

cmks
cmks

Reputation: 537

Your XML code is not well formed. The closing </product> - tag for product 1 is missing. In the 2nd example you have two <product> open tags but no closing one.

Upvotes: 0

Stuart
Stuart

Reputation: 6780

You need to just count($array['products']);

Upvotes: 1

Related Questions