使用php进行高效的JSON解析
我有一个web应用程序,它使用php扫描大量last.fm JSON数据。下面是我目前用来解析它的php使用php进行高效的JSON解析,php,json,Php,Json,我有一个web应用程序,它使用php扫描大量last.fm JSON数据。下面是我目前用来解析它的php <?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']['art
<?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'] as $track) {
$artist = $track['name'];
$image = $track['image'][2]['#text'];
if ($artist&&$image){
echo 'data';
}
}
?>
我目前使用的php可以完成这项工作,但有时似乎速度非常慢。我想知道是否有一种更有效的方法来编写这段代码,从而使其性能更好,或者是因为我在大量数据中运行这段代码,所以速度很慢。非常感谢您的帮助,谢谢 这很可能不是由于您的代码,而是因为下载外部JSON需要一段时间 <>你应该考虑缓存它。 找出问题所在 您可以使用
microtime()
检查问题所在:
JSON解码不会很慢;从API获取JSON的速度会慢得多。不,解码JSON的最快方法是解码JSON。由于外部JSON不在我的网站上,我该如何缓存它。任何帮助都将不胜感激,谢谢您的回复@Eggo我已经用一个简单的缓存解决方案更新了答案(请注意,无论何时缓存中有什么东西,它都不会下载最新版本),这无疑大大缩短了加载时间。非常感谢你的帮助!我真是太感谢你了@Eggo很高兴我能帮上忙——记住我忘记创建缓存文件了——我现在添加了:
file\u put\u contents($localJSONCache,$lfm)代码>。
<?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'] as $track) {
$artist = $track['name'];
$image = $track['image'][2]['#text'];
if ($artist&&$image){
echo 'data';
}
}
$timeEnd = microtime(true);
echo "Time taken to get JSON: " . number_format($timeAfterGet - $timeStart, 4) . " seconds<br />";
echo "Time taken to go through JSON: " . number_format($timeEnd - $timeAfterGet, 4) . " seconds<br />";
?>
<?php
define("MAX_CACHE_LIFETIME", 60 * 60); //1 hour
$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'] as $track) {
$artist = $track['name'];
$image = $track['image'][2]['#text'];
if ($artist&&$image){
echo 'data';
}
}
?>