新浪微博提供的API為JSON格式,我們寫一個PHP指令碼將其轉化成數組並且像表單一樣發布到我們的網站。這就需要使用PHP去類比表單的POST動作,使用CURL庫可以很方便地實現這個需求。
首先是將JSON轉化成數組。
$count = 15;$url = "https://api.weibo.com/2/statuses/home_timeline.json?source=bkjia&count=".$count."&page=1";echo $url.'
';$curl = curl_init();curl_setopt($curl, CURLOPT_URL, $url);// 設定是否顯示header資訊 0是不顯示,1是顯示 預設為0//curl_setopt($curl, CURLOPT_HEADER, 0);// 設定cURL 參數,要求結果儲存到字串中還是輸出到螢幕上。0顯示在螢幕上,1不顯示在螢幕上,預設為0curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);// 要驗證的使用者名稱密碼curl_setopt($curl, CURLOPT_USERPWD, "zhuhaixinwenwang@sina.cn:2639996");$data = curl_exec($curl);curl_close($curl);$result = json_decode($data, true);$post_data = array();for($i = 0; $i < $count; $i++){$post_data['mid'][] = $result['statuses'][$i]['mid'];// 微博id$post_data['title'][] = htmlspecialchars( $result['statuses'][$i]['user']['name'] . ':' . $this -> sysSubStr($result['statuses'][$i]['text'], 50, true) );// 微博標題$post_data['editor'][] = $result['statuses'][$i]['user']['name'];// 微博作者名$post_data['userid'][] = $result['statuses'][$i]['user']['id'];// 微博作者id$post_data['logo'][] = $result['statuses'][$i]['user']['avatar_large'];// 微博作者頭像$post_data['part'][] = '官方微博';// 微博出處if(isset($result['statuses'][$i]['original_pic'])){// 微博原圖$post_data['picture'][$i] = $result['statuses'][$i]['original_pic'];// 微博縮圖$post_data['thumbnail'][$i] = $result['statuses'][$i]['thumbnail_pic'];$post_data['text'][] = $result['statuses'][$i]['text'].'';// 微博內容}else{$post_data['text'][] = $result['statuses'][$i]['text'];// 微博內容}}
然後將數組經過URL編碼編程符合表單POST的字串資料,再使用CURL庫將其POST出去。
for($j = 0; $j < $count; $j++){$o="";foreach($post_data as $k=>$v){$o.= "$k=".urlencode($post_data[$k][$j])."&";}$post_str = substr($o,0,-1);if(file_get_contents($mid_file) == $post_data['mid'][$j]){break;}else{echo urldecode($post_str).'
';$ch = curl_init();curl_setopt($ch, CURLOPT_POST, 1);curl_setopt($ch, CURLOPT_HEADER, 0);curl_setopt($ch, CURLOPT_URL, 'http://x.zhnews.net/post.data.php?db=weibosina');curl_setopt($ch, CURLOPT_POSTFIELDS, $post_str);$result = curl_exec($ch);if(curl_errno($ch)){//出錯則顯示錯誤資訊print curl_error($ch);}}}
再來一個簡單的例子:
$post_data = array();$post_data['clientname'] = "test08";$post_data['clientpasswd'] = "test08";$post_data['submit'] = "submit";$url='http://xxx.xxx.xxx.xx/xx/xxx/top.php';$o="";foreach ($post_data as $k=>$v){ $o.= "$k=".urlencode($v)."&";}$post_data=substr($o,0,-1);$ch = curl_init();curl_setopt($ch, CURLOPT_POST, 1);curl_setopt($ch, CURLOPT_HEADER, 0);curl_setopt($ch, CURLOPT_URL,$url);//為了支援cookiecurl_setopt($ch, CURLOPT_COOKIEJAR, 'cookie.txt');curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);$result = curl_exec($ch);
http://www.bkjia.com/PHPjc/752411.htmlwww.bkjia.comtruehttp://www.bkjia.com/PHPjc/752411.htmlTechArticle新浪微博提供的API為JSON格式,我們寫一個PHP指令碼將其轉化成數組並且像表單一樣發布到我們的網站。這就需要使用PHP去類比表單的POST動作...