Sunday, 15 May 2011

Efficient JSON parsing with php -



Efficient JSON parsing with php -

i have web app uses php scan lot of last.fm json data. here php utilize parse it.

<?php $lfm = file_get_contents('http://ws.audioscrobbler.com/2.0/?method=chart.gettopartists&api_key=apikey&format=json'); $json = json_decode($lfm, true); foreach ($json['artists']['artist'] $track) { $artist = $track['name']; $image = $track['image'][2]['#text']; if ($artist&&$image){ echo 'data'; } } ?>

the php utilize job, seems slow @ times. wondering if there more efficient way write code create perform better, or if slow because running through such big amounts of data. help appreciated, thanks!

it not due code, rather takes while download external json.

you should consider caching it.

finding problem lies

you can check problem lies, using microtime():

<?php $timestart = microtime(true); $lfm = file_get_contents('http://ws.audioscrobbler.com/2.0/?method=chart.gettopartists&api_key=apikey&format=json'); $timeafterget = microtime(true); $json = json_decode($lfm, true); foreach ($json['artists']['artist'] $track) { $artist = $track['name']; $image = $track['image'][2]['#text']; if ($artist&&$image){ echo 'data'; } } $timeend = microtime(true); echo "time taken json: " . number_format($timeafterget - $timestart, 4) . " seconds<br />"; echo "time taken go through json: " . number_format($timeend - $timeafterget, 4) . " seconds<br />"; ?> caching

keep local file - check when file lastly modified , if it's less max_cache_lifetime (in seconds), utilize cached file.

<?php define("max_cache_lifetime", 60 * 60); //1 hr $localjsoncache = "audioscrobbler.json.cache"; $lfm = null; if (file_exists($localjsoncache)) { if (time() - filemtime($localjsoncache) < max_cache_lifetime) { $lfm = file_get_contents($localjsoncache); } } if (empty($lfm)) { $lfm = file_get_contents('http://ws.audioscrobbler.com/2.0/?method=chart.gettopartists&api_key=apikey&format=json'); file_put_contents($localjsoncache, $lfm); } $json = json_decode($lfm, true); foreach ($json['artists']['artist'] $track) { $artist = $track['name']; $image = $track['image'][2]['#text']; if ($artist&&$image){ echo 'data'; } } ?>

php json

No comments:

Post a Comment