Working with PHP’s simplexml and nodes with hyphens

July 21st, 2009 by Tim Leave a reply »

Here’s a quick GOTCHA that may save at least one developer some time. Recently whilst working with some XML to import music into an mp3 download site I came across an issue accessing the values of specific nodes through the simplexml object that I created. The value always threw up zero.

The issue lies in node names containing hyphens, thus:

$object->album-title     returns     0

The answer is to wrap the object property (node name) containing the hyphen in curly braces.

$object->{’album-title’}     returns     “London Calling”

Here’s hoping that helps someone.

Share it:
  • Digg
  • del.icio.us
  • Facebook
  • StumbleUpon
  • LinkedIn
  • Reddit
  • Netvibes
  • Twitthis
  • email
Advertisement

8 comments

  1. Mike says:

    This technique also works for element names with periods in them(incompatible with PHP). Thanks for the info!

  2. Rebecca says:

    Thanks for this tip — it was a huge help to me on a project I was working on.

  3. Pamela says:

    Thank you SO MUCH Tim!!! I was pulling my hair out with this problem and now it’s fixed!!

    Yeah!!

  4. jaronbarends says:

    Exactly what I needed. Thanks!

  5. steven says:

    Thanks for the tip, very helpful. One quick follow up question. Any idea how to deal with hyphens in attributes?

    I’m using the attributes() array to access an external xml file, and here is an example of the problem.

    John Doe

    print_r (person->attributes()) only yields an array with title and salary.

    Thanks for any help.

  6. Martyn Davies says:

    Thanks Tim! This was exactly what I was looking for – only took 3 days to find but so worth it. Cheers!

  7. ignacio lago says:

    Thanks! It’s very hard to find the solution and so easy to solve ;D

  8. Georgie says:

    Cheers bud, a quick google and you saved me a good half hour probably :-)

Leave a Reply