Search code examples
phparraysxmlsimplexml

Get array in object xml (simplexml_load_string)


I have a $xml looks like this

SimpleXMLElement Object
(
    [@attributes] => Array
        (
            [Total] => 450
            [Count] => 4
            [Start] => 0
        )

    [Code] => 0
    [Item] => Array
        (
            [0] => SimpleXMLElement Object
                (
                    [Person.P_Id] => 14845
                )

            [1] => SimpleXMLElement Object
                (
                    [Person.P_Id] => 14844
                )

            [2] => SimpleXMLElement Object
                (
                    [Person.P_Id] => 14837
                )

            [3] => SimpleXMLElement Object
                (
                    [Person.P_Id] => 14836
                )

        )
)

Now I want to get the array Item to merge with another array, but when I try $xml->Item, I only get the first element of this array (which is 14845). When I use count($xml->Item), it returns the true value (which is 4). Did I do something wrong to get the whole array Item?


Solution

  • You don't say whether you want the items as SimpleXMLElements, or just the Person.P_Id values. To get the objects, you can use xpath to get an array:

    $itemobjs = $xml->xpath('//Item');
    print_r($itemobjs);
    

    Output:

    Array
    (
        [0] => SimpleXMLElement Object
            (
                [Person.P_Id] => 14845
            )    
        [1] => SimpleXMLElement Object
            (
                [Person.P_Id] => 14844
            )    
        [2] => SimpleXMLElement Object
            (
                [Person.P_Id] => 14837
            )    
        [3] => SimpleXMLElement Object
            (
                [Person.P_Id] => 14836
            )    
    )
    

    If you just want the Person.P_Id values, you can then iterate that array using array_map:

    $items = array_map(function ($v) { return (string)$v->{'Person.P_Id'}; }, $itemobjs);
    print_r($items);
    

    Output:

    Array
    (
        [0] => 14845
        [1] => 14844
        [2] => 14837
        [3] => 14836
    )
    

    Demo on 3v4l.org