由于我们每天都可以看到 Digg 越来越多地变成一个有趣的图片和视频网站,所以我将注意力转向了 Reddit。 Reddit 似乎更受控制并且对程序员更友好。由于我尊重 Reddit,所以我想我应该编写一个快速教程,介绍如何使用 PHP 检索 URL 的 Reddit 分数。
PHP
<?php /* settings */ $url = 'https://davidwalsh.name/9-signs-not-to-hire-that-web-guy'; $reddit_url = 'http://www.reddit.com/api/info.{format}?url='.$url; $format = 'json'; //use XML if you'd like...JSON FTW! $score = $ups = $downs = 0; //initialize /* action */ $content = get_url(str_replace('{format}',$format,$reddit_url)); //again, can be xml or json if($content) { if($format == 'json') { $json = json_decode($content,true); foreach($json['data']['children'] as $child) { // we want all children for this example $ups+= (int) $child['data']['ups']; $downs+= (int) $child['data']['downs']; //$score+= (int) $child['data']['score']; //if you just want to grab the score directly } $score = $ups - $downs; } } /* output */ echo "Ups: $ups<br />"; //21 echo "Downs: $downs<br />"; //8 echo "Score: $score<br />"; //13 /* utility function: go get it! */ function get_url($url) { $ch = curl_init(); curl_setopt($ch,CURLOPT_URL,$url); curl_setopt($ch,CURLOPT_RETURNTRANSFER,1); curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,1); $content = curl_exec($ch); curl_close($ch); return $content; } ?>
解析 JSON 很简单,使用 json_encode 和 true 的值将 JSON 转换为关联数组。我的示例展示了如何获取“上升”和“下降”的数量——而不仅仅是分数。对于每个 API/Web 服务,我强烈建议缓存您的请求结果。