1. Advertising
    y u no do it?

    Advertising (learn more)

    Advertise virtually anything here, with CPM banner ads, CPM email ads and CPC contextual links. You can target relevant areas of the site and show ads based on geographical location of the user if you wish.

    Starts at just $1 per CPM or $0.10 per CPC.

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>
    SEMrush
     
    Solved! View solution.
    yourwish, Mar 28, 2018 IP
    SEMrush
  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.