Search code examples
phpxmlsimplexml

How to read SimpleXML-Object value where the tag has a special character in it?



Hi guys! I need your help here..
I'm creating a simple XML-Reader in PHP/HTML atm and I've came across a problem.
One XML-Tag has a special character in it ("-") like:

<some-tag>foobar</some-tag>

How do I escape a character, while assigning a variable?

$value = $xml->some-tag

Doesn't work because PHP sees the character as an operator..

I've tried it with:

$value = $xml->'some-tag'

but that 'obviously' didn't work either.
Also this is my first post, so sorry in advance for any mistakes or broken rules.


Solution

  • In PHP you can use the content of a variable as a variable.

    In your case you can do:

    $myTagName = "some-tag";
    $value = $xml->$myTagName;
    

    EDIT
    According to this post https://stackoverflow.com/a/3626928/4641073 you can use:

    $value = $xml->{'some-tag'};