0

I have an XML like this

<items>
  <item>
    <name>A</name>
    <phone>1111111</phone>
  </item>
  <item>
    <name>B</name>
    <phone>2222222</phone>
  </item>
</items>

How can I get the unique nodeNames into an array, like array("name","phone");

1

1 Answer 1

2
$xml = '<items>
  <item>
    <name>A</name>
    <phone>1111111</phone>
  </item>
  <item>
    <name>B</name>
    <phone>2222222</phone>
  </item>
</items>';
$obj = new SimpleXMLElement($xml);
$arr = json_decode(json_encode($obj), TRUE);
$arr = $arr['item'];
var_dump($arr);

Output:

 Array
(
    [0] => Array
        (
            [name] => A
            [phone] => 1111111
        )

    [1] => Array
        (
            [name] => B
            [phone] => 2222222
        )
)

If you want to get the array keys, you can do this:

$keys = array_keys($arr[0]);
var_dump($keys);

Output:

Array
(
    [0] => name
    [1] => phone
)
Sign up to request clarification or add additional context in comments.

5 Comments

"How can I get the unique nodeNames into an array, like array("name","phone");". I asked this because it needs to be dynamic, no matter what the other nodes are named or how many there are, I need an array of unique low-level nodenames, in the format I provided
array_keys($arr[0]) returns array('name', 'phone'). Is that what you mean?
yes! array_keys does what I was looking for, if you want to put that in a separate answer I'll mark it correct
just out of curiosity, is this possible if you didn't know that they are held in a tag node named "item"?
@ejfrancis - With $keys = array_keys($arr);, $keys[0] = 'item';. So you can find it out in that way.

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.