Why does SimpleXML change my array to the array's first element when I use it?

前端 未结 5 1173
予麋鹿
予麋鹿 2021-01-04 20:18

Here is my code:

$string = << 

 
  hello
  there<         


        
5条回答
  •  萌比男神i
    2021-01-04 20:40

    Ah yes, I remember simple XML nearly doing my head in with this parsing arrays issue Try the below code. It will give you an array of LOL elements, or, if you've just got a single LOL element, it will return that in an array as well.

    The main advantage of that is you can do something like foreach ($lol as $element) and it will still work on a single (or on 0) LOL element.

     
       
         
          hello
          there
         
       
    XML;
    
    $xml = simplexml_load_string($string);
    echo "
    ";
    echo "All of the XML:\n";
    print_r($xml);
    
    echo "\n\nJust the 'lol' array:\n";
    
    $test_lols = $xml->testing->children();              
    $childcount = count($test_lols);
    if ($childcount < 2) {
        $lol = array($test_lols->lol);                   
    }
    else {
        $lol = (array) $test_lols;
        $lol = $lol['lol'];
        }
    
    print_r($lol);
    ?>
    

提交回复
热议问题