0

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?

Luu Hoang Bac
  • 433
  • 6
  • 17
  • you need to iterate in `->Item`, where are the codes anyway? you forgot to add them in the post – Kevin Sep 24 '19 at 03:04

1 Answers1

1

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

Nick
  • 138,499
  • 22
  • 57
  • 95
  • Thanks for your answer, this is what I want `$itemobjs = $xml->xpath('//Item');` – Luu Hoang Bac Sep 24 '19 at 03:19
  • I have one more question that I wonder if it's hard. I want to assign another array (with the same format) to the `$xml->Item` array, can I do it? As normal code, I would do something like this `$xml->Item = $new_array`, but in this case, I can't – Luu Hoang Bac Sep 24 '19 at 03:26
  • 1
    Do you mean you want to replace the items in the array? That isn't possible in SimpleXML directly, but you can do it using `DOM`. See this Q&A: https://stackoverflow.com/questions/17661167/how-to-replace-xml-node-with-simplexmlelement-php – Nick Sep 24 '19 at 03:28
  • 1
    If you have problems implementing that code, write up a new question (referring back to that one). – Nick Sep 24 '19 at 03:31