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

LinkShare Web Services Coupon Feed PHP Example

I was working on a PHP page to dynamically generate the links to coupons offered by my advertisers from LinkShare network. Suddenly, LinkShare has terminated my account without a reason. The page is useless now that I am no longer an affiliate.

I am listing my code here so that at least someone can benefit from my work. Note that you need to replace your_token and your_mid with the actual ones. If you omit the mid field, the request includes all your advertisers. Also, do not forget to add error handling to the code to prevent any unsightly errors.

<?php
$url = "http://feed.linksynergy.com/coupon?token=your_token&network=1&mid=your_mid";
$xml = simplexml_load_file($url);
#
echo '<ul>';
foreach ($xml->link as $link)
  {
    echo '<li>';
    echo '<a href="', $link->clickurl, '">';
    echo $link->offerdescription, '</a> ';
    echo ($link->offerenddate=="ongoing"?'':'exp: '.$link->offerenddate);
    echo '<br />';
    echo '</li>';
  }
echo '</ul>';

?>

Here is the sample output.

Get Adobe Flash playerPlugin by wpburn.com wordpress themes