Find Count of Child Elements using PHP

Discussion in 'PHP' started by yourwish, Mar 28, 2018.

  1. #1
    I have xml like following. How i can get count of all "product" elements of the one "order" using PHP. Please help

    <order_0>
    <product_1>product Name</product_1>
    <product_2>product Name</product_2>
    <product_3>product Name</product_3>
    </order_0>
    <order_1>
    <product_1>product Name</product_1>
    <product_2>product Name</product_2>
    </order_1>
     
    Solved! View solution.
    yourwish, Mar 28, 2018 IP
  2. #2
    You can do something like this:

    <?php
    $xml = new simplexmlelement('
    <order_0>
    <product_1>product Name</product_1>
    <product_2>product Name</product_2>
    <product_3>product Name</product_3>
    </order_0>
    ');
    echo count($xml);
    ?>
    Code (markup):
    Working example: https://3v4l.org/IKcfE

    PS another way of doing this:

    http://php.net/manual/en/simplexmlelement.count.php

    
    <?php
    $xml = <<<EOF<people>
    <person name="Person 1">
    <child/>
    <child/>
    <child/>
    </person>
    <person name="Person 2">
    <child/>
    <child/>
    <child/>
    <child/>
    <child/>
    </person>
    </people>EOF;$elem = new SimpleXMLElement($xml);
    
    foreach ($elem as $person) {printf("%s has got %d children.\n", $person['name'], $person->count());
    }?>
    
    Code (markup):
     
    Last edited: Mar 28, 2018
    qwikad.com, Mar 28, 2018 IP
    yourwish likes this.