2

I'm getting stumped by simply trying to get the key/value of a certain tier inside an array I have created from an XML file. The part of the array from Print_R() is:

SimpleXMLElement Object
(
Array
    (
        [category] => SimpleXMLElement Object
            (
                [@attributes] => Array
                    (
                        [settings] => maximum
                    )

                [cat_1] => 5.21
                [cat_2] => 5.05
                [cat_3] => 19.36
                [cat_4] => 21.97
                [cat_5] => 12.17
            )

    )

)

I am trying to get the "cat_1, cat_2, cat_3 .." keys so that I can put them in their own array and use them for other things. I can do print_r($array) and it works, but when I try and do this:

foreach ($array->category as $key => $val) {
$new_array[$key]= "$val";

}

$array->category doesn't seem to target that list. The "SimpleXMLElement Object" from the XML file seems to be in the way of how I normally use arrays. Does anyone know how I can get to those cat_1 ets. lists?

0

2 Answers 2

1

Notice that $array->category is an object, not an array and cat_* are properties. Since they are all public just use:

$new_array = get_object_vars($array->category);
Sign up to request clarification or add additional context in comments.

1 Comment

Perfect, I did not know about get_object_vars, that makes sense. Just tried and it's what I needed to move forward. Thanks!
0

You should convert simpleXML object to array using

$array = json_decode(json_encode((array) $simplexmlob)), 1);

Then use $array['category'] for other things. There is no need to use foreach loop.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.