/PHP XML Problem – Hyphen in the Element Name

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'};