首页 话题 小组 问答 好文 用户 我的社区 域名交易

[分享]PHP查询百度收录与排名

发布于 2025-03-20 23:43:25
0
33

PHP实现批量查询关键词百度收录与排名,演示代码如下:

/*
 * 收录、排名
 *
 * @access public
 * @return void
 */
public function checkGather(){
	$keyword = urldecode(I('get.txt'));
	$url = urldecode(I('get.url'));
	$baiduIP = I('get.baiduIP') ? I('get.baiduIP') : 'www.baidu.com';
	if(empty($keyword) || empty($url)){
		header('HTTP/1.0 404 Not Found');
		exit();
	}

	$data = array('index_state'=>0, 'gather_state'=>0);
  
	//获得网址内容
	$gatherContent = @file_get_contents("http://{$baiduIP}/s?wd=". urlencode($url) ."&pn=0");  
	if(strstr($gatherContent, '验证码')){
		preg_match('/<input[^>]*name="url"[^>]*value="([^>]*)">/', $gatherContent, $baiduUrl);
		$gatherContent = @file_get_contents($baiduUrl[1]);
	}

	//检查是否收录
	if(!strstr($gatherContent, iconv('gbk','utf-8','没有找到该URL')) && !strstr($gatherContent, iconv('gbk','utf-8','抱歉,没有找到'))){
		$data['gather_state'] = 1;
		//获得首页内容
		$enKeyword = urlencode($keyword);
		$indexContent = @file_get_contents("http://{$baiduIP}/s?wd=$enKeyword&pn=0");

		//首页内容是否出现该域名
		$ulrArray = explode('.', $url);
		$domain = (count($ulrArray) <= 2) ? str_replace('http://', '', $ulrArray[0]) : $ulrArray[1];
		preg_match("/$domain/",$indexContent,$domainExists);

		if($domainExists){
			$indexArray = preg_split('/class="result[^>]*?id="\d{1,2}"/', $indexContent);
			array_shift($indexArray);

			//循环检查是否存在首页
			$p = 0;
			$regexCache = '/<a[^>]*href="([^\s]*)"[^>]*>/';

			foreach($indexArray as $v){
				$p++;

				//获得快照内容
				preg_match($regexCache, $v, $indexCacheResult);
				$header = get_headers($indexCacheResult[1],1);
				$domain = is_array($header['Location']) ? $header['Location'][0] : $header['Location'];

				//匹配URL
				if($url == $domain){
					$data['index_state'] = $p;
					break;
				}
			}

			unset($gatherContent);
			unset($indexContent);
			unset($indexCacheContent);
		}
	}
	echo json_encode($data);
}
评论
站长交流