网页自动发布到新浪微博和Facebook

自己的网站建立两年有余,现在没啥精力更新,移动浪潮袭来,web应用式微,网站的流量越来越少。前段时间再次看到关于“流量为王”的网站发展传说,于是打算把之前发布的网站文章链接分享到新浪微博和Facebook,多多少少去引入点流量。

1、微博自动发布

根据微博API接口资料,通过API发布微博需要Oauth登陆1111

222

因为我计划通过Linux服务器crontab定时发布,且是免登陆的自动发布,所以首先需要微博用户(我使用开发者本人的微博)登陆并获取access_token(7天有效)。

获取access_token的方法可以参考这里祺爸PiscDong / weibo_PHP

使用祺爸PiscDong / weibo_PHP 代码的demo.php实例获取access_token

<?php
session_start(); //此示例中要使用session
require_once('config.php');
require_once('sina.php');

function getimgp($u){
	//图片处理
	$c=@file_get_contents($u);
	$name=md5($u).'.jpg';
	$mime='image/unknown';
	return array($mime, $name, $c);
}

$sina_t=isset($_SESSION['sina_t'])?$_SESSION['sina_t']:'';

//检查是否已登录
if($sina_t!=''){
	$sina=new sinaPHP($sina_k, $sina_s, $sina_t);

	//获取登录用户id
	$sina_uid=$sina->get_uid();
	$uid=$sina_uid['uid'];

	//获取登录用户信息
	$result=$sina->show_user_by_id($uid);
	var_dump($result);

	/**
	//发布微博
	$content='微博内容';
	$img='http://www.baidu.com/img/baidu_sylogo1.gif';
	$img_a=getimgp($img);
	if($img_a[2]!=''){
		$result=$sina->update($content, $img_a);
		//发布带图片微博
	}else{
		$result=$sina->update($content);
		//发布纯文字微博
	}
	var_dump($result);
	**/

	/**
	//微博列表
	$result=$sina->user_timeline($uid);
	var_dump($result);
	**/

	/**
	//其他功能请根据官方文档自行添加
	//示例:根据uid获取用户信息
	$result=$sina->api('users/show', array('uid'=>$uid), 'GET');
	var_dump($result);
	**/

}else{
	//生成登录链接
	$sina=new sinaPHP($sina_k, $sina_s);
	$login_url=$sina->login_url($callback_url);
	echo '<a href="',$login_url,'">点击进入授权页面</a>';
}

获取成功后,因为access_token 7天内有效,可以直接把该access_token当做参数,通过API直接发布,代码示例如下:

<?php
session_start(); //此示例中要使用session
require_once('config.php');
require_once('sina.php');
function getimgp($u){
	//图片处理
	$c=@file_get_contents($u);
	$name=md5($u).'.jpg';
	$mime='image/unknown';
	return array($mime, $name, $c);
}

$sina_k='xxxxxxxxxxxx'; //新浪微博应用App Key
$sina_s='xxxxxxxxxxxx'; //新浪微博应用App Secret
$sina_t='xxxxxxxxxxxx'; //登录用户的Access_Token

//发布微博
$content='微博内容';
$img='http://www.baidu.com/img/baidu_sylogo1.gif';
$img_a=getimgp($img);
if($img_a[2]!=''){
	$result=$sina->update($content, $img_a);
	//发布带图片微博
}else{
	$result=$sina->update($content);
	//发布纯文字微博
}
var_dump($result);
?>

因为打算利用Linux Crontab定时发布,编写了如下Shell代码

#!/bin/sh
tl="/home/wwwroot/xxx/sitemap.txt" #!sitemap为我需要发布网址列表
tl2=$(head -1 $tl)   #!读取txt文件第一行
sleep 2s
tl3="http://xxx.com/demo2.php?url="$tl2"" 
/usr/local/bin/lynx -source $tl3 #!通过lynx模拟浏览器访问,同时向php网页传参
sleep 10s
sed -i '1d' $tl #!删除txt文件第一行
sleep 4s

另外我尝试了使用simple_html_dom.php这个库简单爬取网页信息,作为微博内容,自动发布。爬虫的使用办法可以参考这里http://blog.sina.com.cn/s/blog_5fd841bf0100dqk2.html

 

2、facebook自动发布到粉丝页面上

第一次尝试参考《讓使用者免登入直接透過 Facebook API 發佈訊息到粉絲頁上》http://blog.chrisflicker.com/post/88074551173办法自动发布,后google得知此方法已失效。

最后在http://stackoverflow.com/(点击打开)找到了正确的代码。

摘录如下(该答案作者不但给出了使用Facebook原生SDK自动发布的办法,并提供获取永久Access_Token的办法,链接

session_start();
define('FACEBOOK_SDK_V4_SRC_DIR', 'facebook-php-sdk-v4-4.0-dev/src/Facebook/');
require __DIR__ . '/facebook-php-sdk-v4-4.0-dev/autoload.php';

use Facebook\FacebookSession;
use Facebook\FacebookRequest;
use Facebook\GraphUser;
use Facebook\FacebookRequestException;
use Facebook\FacebookRedirectLoginHelper;

// Facebook App
$api_key    = 'xxxxxxxxxxxxxxxx'; //App ID
$api_secret = 'xxxxxxxxxxxxxxxx'; //App Secret
$page_id    = 'xxxxxxxxxxxxxxxx'; //Page ID
$page_token = 'from the steps in the url';  
$fb_post    = array(
                'message'=> 'test message',
                'name'=>    '',
                'link'=>    'http://www.example.com/',
                'picture'=> 'http://www.example.com/image.jpg',
                'caption'=> '',
    );

// start a session for this App
FacebookSession::setDefaultApplication($api_key, $api_secret);

try {
  $session = new FacebookSession($page_token);
} catch(FacebookRequestException $e) {
    die(" Error : " . $e->getMessage());
} catch(\Exception $e) {
    die(" Error : " . $e->getMessage());
}

try {
// Auto posting
    $page_post = (new FacebookRequest( $session, 'POST', '/'. $page_id .'/feed', $fb_post))->execute()->getGraphObject()->asArray();
// return post_id, optional
    print_r( $page_post );
} catch (FacebookRequestException $e) {
  // The Graph API returned an error
    echo '<b style="color:blue;">'.$e->getMessage().'</b>';
} catch (\Exception $e) {
  // Some other error occurred
    echo '<b style="color:red;">'.$e->getMessage().'</b>';
}

另外这一次我尝试了使用curl来简单爬取网页Meta信息,作为Facebook相关内容,自动发布。curl爬网页Meta使用办法可以参考这里使用curl获取页面的meta中keywords和description

<?php

/**
 * 使用cURL获取一个网页中的 keyword 和 description 部分
 * 
 * @param str $ 查询的url地址
 * @return array array('keyword'=>keyword部分,'description'=>description部分)
 */
function curl_getkd($url) {
	$ch = curl_init();
	curl_setopt($ch, CURLOPT_URL, $url); 
	curl_setopt($ch, CURLOPT_HEADER, 1); 
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	$html = curl_exec($ch);
	$info = curl_getinfo($ch);
	if ($html === false) {
		echo "cURL Error: " . curl_error($ch);
	} 
	curl_close($ch);
	preg_match_all("/<meta[^>]+name=\"([^\"]*)\"[^>]" . "+content=\"([^\"]*)\"[^>]*>/i", $html, $r, PREG_PATTERN_ORDER);
	for ($i = 0;$i < count($r[1]);$i++) {
		if (strtolower($r[1][$i]) == "keywords") $meta['keywords'] = $r[2][$i];
		if (strtolower($r[1][$i]) == "description") $meta['description'] = $r[2][$i];
	} 
	return $meta;
} 
// 测试
$r = curl_getkd('http://www.qq.com/');
echo '<pre>';
print_r($r);
echo '</pre>';
// 输出
/**
  Array
  (
 [keywords] => ……
  [description] => ……
  )
 */

?>

后记:

由于自己从没写过分享教程类的文章,而且php是自学的三脚猫水平。各位看官见谅。

通过最近这次学习(百度+google找答案,边试边改的模式),学到了Oauth登录,API使用,Shell代码编写,Crontab服务的使用,第三方爬虫simple_html_dom及Curl爬网页等方面的一些知识。另外http://stackoverflow.com/对于查找编程问题解决办法非常有效!

完。

Posted in 未分类

发表评论

邮箱地址不会被公开。 必填项已用*标注