Nicoli
Nicoli

Reputation: 944

How to get correct count on XML on PHP

Consider this:

<?xml version="1.0" encoding="UTF-8"?>
<response  Version="1.0">
  <product code_product="8989" description="Pen" model="ECOPEN" box_ext_pz="1000" box_int_pz="50">
    <color  code_color="00" name_color="WHITE">
        <stock>556</stock>
        <arrive>0</arrive>
        <date_arrive>2019-09-20</date_arrive>
    </color>
    <color  code_color="20" name_color="BLUE">
        <stock>7895</stock>
        <arrive>0</arrive>
        <date_arrive>2019-09-20</date_arrive>
    </color>
    <color  code_color="30" name_color="RED">
        <stock>7205</stock>
        <arrive>0</arrive>
        <date_arrive></date_arrive>
    </color>
  </product>
  <product  code_product="9000" description="Heart" model="KISS" box_ext_pz="500" box_int_pz="50">
    <color  code_color="20" name_color="BLUE">
        <stock>6</stock>
        <arrive>0</arrive>
        <date_arrive></date_arrive>
    </color>
  </product>
</response>

I need to know number of colors of each one:

// All of the products are in one xml file
$xmlstring = file_get_contents("all.xml");
$products = simplexml_load_string($xmlstring);
// Get total of products
$count = count($products['product']); // Returns correct number

for($cc=0;$cc<$count;$cc++) {
    echo $products['product'][$cc]['@attributes']['description']; // OK
    echo " " . $products['product'][$cc]['@attributes']['model']; // OK
    echo " " . $products['product'][$cc]['@attributes']['box_ext_pz']; // OK
    $colors = count($products['product'][$cc]['color']);
    echo " $colors "; // WRONG
}

In both products, 8989 and 9000, I get 3 colors, which is incorrect for the product code "9000".

How to get correct number of colors?

Upvotes: 0

Views: 31

Answers (1)

Nigel Ren
Nigel Ren

Reputation: 57141

Your code in the loop is not standard and you should be using -> notation for the child elements and [] for attributes.

So in this code, $products->product is the individual product elements and $product['description'] is the description attribute...

foreach ( $products->product as $product )  {
    echo $product['description']; 
    echo " " . $product['model']; 
    echo " " . $product['box_ext_pz']; 
    $colors = count($product->color);
    echo " $colors ".PHP_EOL; 
}

gives...

Pen ECOPEN 1000 3 
Heart KISS 500 1 

Upvotes: 1

Related Questions