简体   繁体   中英

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?

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

You should read the documentation for the RecursiveIteratorIterator constructor . Reproducing the relevant portion here:

Optional mode . Possible values are

  • RecursiveIteratorIterator::LEAVES_ONLY - The default. Lists only leaves in iteration.
  • RecursiveIteratorIterator::SELF_FIRST - Lists leaves and parents in iteration with parents coming first.
  • RecursiveIteratorIterator::CHILD_FIRST - Lists leaves and parents in iteration with leaves coming first.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM