将spotify json文件转换为html

时间:2015-12-13 21:40:50

标签: php html json spotify

我正在尝试将spotify json文件转换为html表。但是这个json文件有点复杂。我在某个地方犯了一个错误,但无法找出我做错了什么。什么是正确的代码?

<?php
    $spotifylist = "http://spotifycharts.com/api/?type=regional&country=nl&recurrence=daily&date=latest&limit=200";
    $contents = file_get_contents($spotifylist); 
    $decoded = json_decode($contents,true); 
    $results = $decoded->entries[0]->items;

    echo "<table class='chart'> <thead><tr class='row2'><th class='dw'></th><th class='song'>Artiest</th><th class='song'>Titel</th></tr></thead><tbody>";      

    foreach($results as $entry){
      $artist = $entry->track->artists->name;
      $name = $entry->track->name;
      $x = $entry + 1;  
      $color = ($x%2 == 0)? 'row2': 'row1'; 
      echo "<tr class='$color'>";   
        echo "<td class='dw'>". $x ."</td>"; 
        echo "<td class='song'>". $artist ."</td>";
        echo "<td class='song'>". $name ."</td>";
      echo "</tr>";  
    }
    echo "</tbody></table>";
?>

问候

1 个答案:

答案 0 :(得分:0)

您的代码有点混乱。我已经清理了一点以便它可以正常工作,但我认为你需要更仔细地查看它 - 它会从Feed中提取非常精确的数据,这可能不会安全。

以下工作代码:

<?php
    $spotifylist = "http://spotifycharts.com/api/?type=regional&country=nl&recurrence=daily&date=latest&limit=200";
    $contents = file_get_contents($spotifylist); 
    $decoded = json_decode($contents); 
    $results = $decoded->entries->items;

    echo "<table class='chart'> <thead><tr class='row2'><th class='dw'></th><th class='song'>Artiest</th><th class='song'>Titel</th></tr></thead><tbody>";      

    $counter = 0;

    foreach($results as $entry){
        ++$counter;

        $artist = (string)$entry->track->artists[0]->name;
        $name = $entry->track->album->name;
        $color = ($counter % 2 == 0) ? 'row2': 'row1'; 
        echo "<tr class='$color'>";   
        echo "<td class='dw'>$counter</td>"; 
        echo "<td class='song'>". $artist ."</td>";
        echo "<td class='song'>". $name ."</td>";
        echo "</tr>";  
    }

    echo "</tbody></table>";
?>