• PHP Simple XML Handle Attributes and Count Elements

    Posted by markzero on Sunday, January 2nd, 2011

    If you’re a beginner in using XML in PHP then this short tutorial might help you understand things. PHP offers a package Simple XML which can handle code in XML file or string which forms an XML.

    Two main things you should take special look at are count elements and getting attributes from an element (may be root element as well). So, let’s take a look at this XML string:

     
    <?php
    $xml_str = '<rootelement size="2" attr="foo">
       <element>
          <subelement>value1</subelement>
       </element>
       <element>
          <subelement>value2</subelement>
       </element>
    </rootelement>';
    ?>

    To load a string (which can be also pulled from a file) simplexml_load_string method is used, this way:

     
    <?php
    $xml = simplexml_load_string($xml_str);
    ?>

    What we notice here is attributes on root element, and element node appears two times. Simple XML creates tree out of an XML structure. PHP has count method, which returns how many times a node repeats. If we want to create a loop to go through any XML structure, then this is the way to go:

     
    <?php
    for($i=0;$i<count($xml->element);$i++) {
       // do stuff here but access subelements this way:
       $x = $xml->element[$i]->subelement;
    }
    ?>

    To access attributes of any node, just do this:

     
    <?php
    // this will display "2" without quotes
    $xml->attributes()->size;
    // this will display "foo" without quotes
    $xml->attributes()->attr;
    ?>

    Pretty cool, easy and effective.

    More on XML to come… If you have any comments, just ask below $darr;

    Posted in: PHP, XML.

    Share this story:

    2 responses to “PHP Simple XML Handle Attributes and Count Elements”

    1. Ayoyemi says:

      Really helpful tutorial,
      Thanks

      Report this comment

    2. Teslina says:

      Thank you very much! That saved me some time :-)

      Report this comment

    Leave a Reply