在php中解析巨大的json文件

时间:2014-07-19 04:25:20

标签: php json parsing

这是我的问题!我有一个巨大的json文件,我想解析(这里是链接:http://pastebin.com/JwPDufMx) 我想提取它所有的歌曲以填充不同的数组,如ID / TITLE / GENRE / ARTWORK_URL

我试过这一行

$json_file = file_get_contents('playlist.json');
$jfo = json_decode($json_file);
for ...  { //don't know how to make this loop to end well despite infinite
$id[$i] = $jfo->tracks->track->id
...
}

但它不起作用。 我想知道如何使其正确并提取我需要的数据:D

提前感谢您的帮助!

1 个答案:

答案 0 :(得分:1)

您的测试数据显示有多个播放列表。下面的代码通过平衡开始和结束括号一次提取一个播放列表。然后在每个播放列表json上使用json_decode。

$json = file_get_contents('playlist.json');
$depth = 0;
$playlist_json = '';
$tracks = array();

for ($i = 0; $i < strlen($json); $i++) {
    $char = $json[$i];
    if ($char == '{') {
        $depth++;
    } elseif ($char == '}') {
        $depth--;
    }

    if ($char == '{' || strlen($playlist_json) > 0) {
        $playlist_json .= $char;
    }

    if ($depth == 0 && strlen($playlist_json) > 0) {
        $playlist = json_decode($playlist_json, true);
        $tracks = array_merge($tracks, $playlist['tracks']);
        $playlist_json = '';
    }
}

foreach ($tracks as $track) {
    echo $track['id'] . "\n";
    echo $track['title'] . "\n";
    echo $track['genre'] . "\n";
    echo $track['artwork_url'] . "\n\n";
}

在测试数据上使用它会产生:

155675361
Tegan and Sara - I Was A Fool (Bolivard Remix) *FREE DOWNLOAD IN DESCRIPTION*
Deep Pop
http://i1.sndcdn.com/artworks-000083195650-0wlzyr-large.jpg?e76cf77

156088370
Mariah Carey - Emotions (LBCK Rmx)
LBCK
http://i1.sndcdn.com/artworks-000083458530-wq93hc-large.jpg?e76cf77

156520409
Topi x Tontario - Backfeed
Chill
http://i1.sndcdn.com/artworks-000083734122-2i0zh1-large.jpg?e76cf77

157430720
SG Lewis - Silence (Art Of Shades Re-Work)
Sensitive
http://i1.sndcdn.com/artworks-000084379509-8dq1aa-large.jpg?e76cf77

156707981
Tender Games - Lost (BBC Radio 1 l Annie Mac - 29.06.2014)
Tender Games
http://i1.sndcdn.com/artworks-000083857078-f1axpw-large.jpg?e76cf77

158508920
Sailor & I - Tough Love (Phonothek Remix)
Deep-House
http://i1.sndcdn.com/artworks-000085049173-5w358k-large.jpg?e76cf77

158261593
Garde Le Pour Toi

http://i1.sndcdn.com/artworks-000084889721-lhpg98-large.jpg?e76cf77

158384606
Damian Marley - Road To Zion ( EFIX & XKAEM Cover )
deep
http://i1.sndcdn.com/artworks-000084969076-tk9e3x-large.jpg?e76cf77

159111023
Clara Moto - In My Dream (Ferdinand Remix)
Ferdinand
http://i1.sndcdn.com/artworks-000085458717-m1nhj1-large.jpg?e76cf77
相关问题