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

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

Here is my code:

$string = << 

 
  hello
  there<         


        
5条回答
  •  灰色年华
    2021-01-04 20:32

    What @Yottatron suggested is true, but not at all the cases as this example shows :

    if your XML would be like this:

    
    
        
            Lol1
            Lol2
            NotLol1
            NotLol1
        
    
    

    Simplexml's output would be:

    SimpleXMLElement Object
    (
    [lol] => SimpleXMLElement Object
        (
            [lolelem] => Array
                (
                    [0] => Lol1
                    [1] => Lol2
                )
    
            [notlol] => Array
                (
                    [0] => NotLol1
                    [1] => NotLol1
                )
    
        )
    
    )
    

    and by writing

    $xml->lol->lolelem
    

    you'd expect your result to be

    Array
    (
         [0] => Lol1
         [1] => Lol2
    )
    

    but instead of it, you would get :

    SimpleXMLElement Object 
    (
        [0] => Lol1
    )
    

    and by

    $xml->lol->children()
    

    you would get:

    SimpleXMLElement Object
    (
    [lolelem] => Array
        (
            [0] => Lol1
            [1] => Lol2
        )
    
    [notlol] => Array
        (
            [0] => NotLol1
            [1] => NotLol1
        )
    
    )
    

    What you need to do if you want only the lolelem's:

    $xml->xpath("//lol/lolelem")
    

    That gives this result (not as expected shape but contains the right elements)

    Array
    (
        [0] => SimpleXMLElement Object
        (
            [0] => Lol1
        )
    
        [1] => SimpleXMLElement Object
        (
            [0] => Lol2
        )
    
    )
    

提交回复
热议问题