reddit_使用PHP和JSON获取URL的Reddit分数

reddit

Reddit Guy

Since we can see Digg turning more into a funny-pic-and-vid site each day, I've turned my attention to Reddit. Reddit just seems more controlled and programmer-friendly. Since I have respect for Reddit I thought I'd put together a quick tutorial on how you can retrieve a URL's Reddit score using PHP.

由于我们每天都能看到Digg变成一个有趣的生动视频网站,因此我将注意力转向Reddit。 Reddit似乎更具控制​​性且对程序员更友好。 由于我尊重Reddit,所以我想整理一个快速教程,介绍如何使用PHP检索URL的Reddit分数。

PHP (The 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;
	}

?>

Parsing the JSON is simple using json_encode with the value of true to make turn the JSON into an associate array. My example shows how you can grab the number of "ups" and "downs" -- not just the score. As with every API/web service, I highly recommend caching the result of your request.

使用json_encode和true值来解析JSON很简单,可以将JSON转换为关联数组。 我的示例显示了如何获取“上升”和“下降”的数量-而不仅仅是分数。 与每个API / Web服务一样,我强烈建议您缓存请求的结果。

翻译自: https://davidwalsh.name/get-reddit-score

reddit

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值