Working with PHP’s simplexml and nodes with hyphens

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.

  • Twitter
  • Facebook
  • Digg
  • del.icio.us
  • StumbleUpon
  • LinkedIn
  • Reddit
  • Netvibes
  • email

11 comments

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

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

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

    Yeah!!

  4. Exactly what I needed. Thanks!

  5. 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

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

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

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

  9. Got stuck with a dot and found this. Thanks!

  10. Just thought I would let you know that I found this page first search in google for my issue. Your explanation was concise and you saved me a bucket load of time.

    I thank you very very much

  11. Smashing mate. The LinkedIn api is a pile of crap, using hyphens throughout their node names. This helped loads, thanks.

Leave a comment