3

I have an xml document with tags that have two dashes in them, like so: <item--1>. I'm using SimpleXML to parse this document, so it gives me object properties with the name of the tag. This apparently is a problem, I guess because dashes are invalid characters for variable and property names.

<?php

$xml = "<data><fruits><item>apple</item><item--1>bananna</item--1></fruits></data>";

$xml = simplexml_load_string($xml);

foreach( $xml->children() as $child ) {
  var_dump($child->item);
#  var_dump($child->item--1);
}

When you run this, you get

object(SimpleXMLElement)#5 (1) {
  [0]=>
  string(5) "apple"
}

But if you uncomment the last line, the xml element with two dashes, you get an error:

PHP Parse error:  syntax error, unexpected T_LNUMBER in test.php on line 17

I tried using curly braces:

var_dump($child->{item--1});

But that only gave me this error:

PHP Parse error:  syntax error, unexpected T_DEC

which is the decrement operator, or --.

How can I reference the properties on this object?

user151841
  • 17,377
  • 29
  • 109
  • 171
  • What does `var_dump($child)` yield? – Brad Christie Sep 06 '12 at 22:29
  • `object(SimpleXMLElement)#4 (2) { ["item"]=> string(5) "apple" ["item--1"]=> string(7) "bananna" } ` which, while it doesn't break, doesn't really allow me to access data. They're not array elements that I can reference. – user151841 Sep 06 '12 at 22:31

2 Answers2

7

Your approach with the curly braces wasn't too wrong, but you need a string between the braces:

var_dump($child->{'item--1'});
Mark
  • 6,033
  • 1
  • 19
  • 14
1

From the manual's page on SimpleXMLElement object:

Warning to anyone trying to parse XML with a key name that includes a hyphen ie.)

<subscribe>
  <callback-url>example url</callback-url>
</subscribe>

In order to access the callback-url you will need to do something like the following:

<?php
  $xml = simplexml_load_string($input);
  $callback = $xml->{"callback-url"};
?>

If you attempt to do it without the curly braces and quotes you will find out that you are returned a 0 instead of what you want.

Brad Christie
  • 100,477
  • 16
  • 156
  • 200