Search code examples
phpsimplexml

Php, SimpleXMLIterator, RecursiveIteratorIterator


I am trying to understand a small part of a code I am studying, This is the Link to the code, the part i did not understand is this:

new RecursiveIteratorIterator($it, 1)

What I didn't understand about this part is the second parameter, I tried to play with the value of this parameter and I assume it's about the XML structure but the logic with it is a bit odd, So if anyone can please clarify to me about this second parameter?


Solution

  • Ok let me break it down

    What you need to first understand is this line :

     $it = simplexml_load_string($xmlstring, 'SimpleXMLIterator');
    

    From PHP DOC

    You may use this optional parameter so that simplexml_load_string() will return an object of the specified class.

    This means that all output would use SimpleXMLIterator and the best way to iterate is using RecursiveIteratorIterator

    Recursion is the process of repeating items in a self-similar way. See wiki

    Example

    $xml = '
    <movies>
      <movie>abcd</movie>
      <movie>efgh</movie>
      <movie>
        <name> Test </name>
        <type> Action </type>   
        </movie>    
    </movies>';
    
    
    echo "<pre>" ;
    echo "With Just SimpleXmlIterator\n";
    
    foreach (new SimpleXmlIterator($xml) as $value ) {
        print($value . PHP_EOL);
    }
    
    
    echo "<pre>" ;
    echo " RecursiveIteratorIterator \n";
    
    foreach (new RecursiveIteratorIterator  (new SimpleXmlIterator($xml)) as $value ) {
        print(trim($value) . PHP_EOL);
    }
    

    Output 1

    With Just SimpleXmlIterator
    abcd
    efgh
    

    Output 2

    RecursiveIteratorIterator 
    abcd
    efgh
    Test
    Action