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?
Your approach with the curly braces wasn't too wrong, but you need a string between the braces:
var_dump($child->{'item--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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With