TapParsing XML with PHP

Following on from the last.fm saga described earlier, I went on to look at the method user.GetWeeklyAlbumChart which requires accessing user.GetWeeklyChartList first.

I am using the plugin iLast.Fm from Leandro Alonso and the code he is using looks right but doesn’t seem to work. He uses curl to get the XML from the last.fm site. The XML you get is of the form

<lfm status="ok">
<weeklychartlist user="[username]">
<chart from="1225022400" to="1225627200"/>
<chart from="1225627200" to="1226232000"/>
<chart from="1226232000" to="1226836800"/>
</weeklychartlist>
</lfm>

He then parses it with simplexml_load_file() and puts it into an object called $chart. Then the code processes this as follows

$chartopt = sizeof($chart->weeklychartlist->chart) - 1;
$chart = $chart->weeklychartlist->chart[$chartopt];

and uses $chart['from'] and $chart['to'] in the call to user.GetWeeklyAlbumChart.

The problem is that $chartopt always has the value 0 which means that the sizeof() function is not working properly. There is a comment on the PHP documenattion page which says that foreach doesn’t work but reccomends count/sizeof() instead. What can be wrong?

Update: The answer seems to be here: SimpleXML is not so simple and it doesn’t behave correctly. It needs

$chartopt = -1;
foreach($chart->weeklychartlist->chart as $i) $chartopt++;

Comments are closed.

^ Top