PHP XML Problem – Hyphen in the Element Name

I have been playing with PHP and web services lately. As I did not learn PHP from the ground up, I just tried to assemble my code base upon the examples I gathered. One problem puzzled me for a long time. I didn’t figure out what the problem is until I rewrote the program in PowerShell.

I have used Simple XML to parse an XML document. There are multiple links in this document. I iterated the links array to print out the information. Problem is I can print out some elements, but not the others. For example, this works:

echo $link->description;

However, this does not work:

echo $link->link-code-html;

I worked on this particular problem for an afternoon, but I could not figure out what was wrong. It’s hard to debug using PHP, so I decided to use PowerShell to rewrite the program and see if I could replicate the same “error”.  I did get the same problem. In PowerShell, dot notation is used and I cannot print this, either:

echo $link.link-code-html

I later learned that the hyphen is interpreted as minus sign. I had to modify the the PowerShell code to:

echo $link.Item('link-code-html')

With this information in mind, I know the hyphen in the XML element name is the cause. The online manual for PHP SimpleXML has one  example. So, my original code has to be modified to

echo $link->{'link-code-html'};

This post may contain affiliated links. When you click on the link and purchase a product, we receive a small commision to keep us running. Thanks.


6 Comments

  1. Thank you very much for posting this solution! I was in my second week of casual research about why some of my displays were not generating PHP syntax failures (blank screens), but were not displaying the data (even format) that I expected. Thanks to this post, I am back on track, again, and I am very, very appreciative for this post!

1 Trackback / Pingback

  1. SimpleXML fix « Blog | Nick Fehr

Leave a Reply