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");

ejfrancis
  • 2,925
  • 4
  • 26
  • 42

1 Answers1

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
)
Expedito
  • 7,771
  • 5
  • 30
  • 43
  • "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 – ejfrancis Jul 17 '13 at 16:28
  • 1
    `array_keys($arr[0])` returns `array('name', 'phone')`. Is that what you mean? – Expedito Jul 17 '13 at 17:49
  • yes! array_keys does what I was looking for, if you want to put that in a separate answer I'll mark it correct – ejfrancis Jul 18 '13 at 00:23
  • just out of curiosity, is this possible if you didn't know that they are held in a tag node named "item"? – ejfrancis Jul 18 '13 at 20:53
  • @ejfrancis - With `$keys = array_keys($arr);`, `$keys[0] = 'item';`. So you can find it out in that way. – Expedito Jul 18 '13 at 20:57