php实现专业获取网站SEO信息类实例


Posted in PHP onApril 02, 2015

本文实例讲述了php实现专业获取网站SEO信息类。分享给大家供大家参考。具体如下:

这个seo类的功能包括:
- 检查指定的网站响应
- 获取从该网站主页的语言和其他meta标签数据的
- 获取网站的导入链接,从Alexa的流量排名
- 获取网站的导入链接,由谷歌索引的网页数量
- 获取网站的信任,从WOT排名。
- 获取,因为它是第一个注册的网站域名年龄
- 获取的Twitter网站页面的数量
- 获取的Facebook链接的网站页面
- 获取网站谷歌网页速度等级
- 获取网站的谷歌网页排名

<?php
/**
 *
 * SEO report for different metrics
 *
 * @category SEO
 * @author Chema <chema@garridodiaz.com>
 * @copyright (c) 2009-2012 Open Classifieds Team
 * @license GPL v3
 * Based on seo report script http://www.phpeasycode.com && PHP class SEOstats
 *
 */
class seoreport{
  /**
   *
   * check if a url is online/alive
   * @param string $url
   * @return bool
   */
  public static function is_alive($url)
  {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
    curl_setopt($ch, CURLOPT_HEADERFUNCTION, 'curlHeaderCallback');
    curl_setopt($ch, CURLOPT_FAILONERROR, 1);
    curl_exec ($ch);
    $int_return_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close ($ch);
    if ($int_return_code != 200 && $int_return_code != 302 && $int_return_code != 304)
    {
      return FALSE;
    }
    else return TRUE;
  }
  /**
   * HTTP GET request with curl.
   *
   * @param string $url String, containing the URL to curl.
   * @return string Returns string, containing the curl result.
   *
   */
  protected static function get_html($url)
  {
    $ch = curl_init($url);
    curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
    curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,5);
    curl_setopt($ch,CURLOPT_FOLLOWLOCATION,1);
    curl_setopt($ch,CURLOPT_MAXREDIRS,2);
    if(strtolower(parse_url($url, PHP_URL_SCHEME)) == 'https')
    {
      curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,1);
      curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,1);
    }
    $str = curl_exec($ch);
    curl_close($ch);
    return ($str)?$str:FALSE;
  }
  /**
   *
   * get the domain from any URL
   * @param string $url
   */
  public static function domain_name($url)
  {
    $nowww = ereg_replace('www\.','',$url);
    $domain = parse_url($nowww);
    if(!empty($domain["host"]))
      return $domain["host"];
    else
      return $domain["path"];
  }
  /**
   *
   * get the metas from a url and the language of the site
   * @param string $url
   * @return array
   */
  public static function meta_info($url)
  {
    //doesn't work at mediatemple
    /*$html = new DOMDocument();
    if(!$html->loadHtmlFile($url))
      return FALSE;*/
    if (!$html_content = self::get_html($url))
        return FALSE;
    $html = new DOMDocument();
    $html->loadHtml($html_content);
       
    $xpath = new DOMXPath( $html );
    $url_info = array();
    $langs = $xpath->query( '//html' );
    foreach ($langs as $lang)
    {
      $url_info['language'] = $lang->getAttribute('lang');
    }
    $metas = $xpath->query( '//meta' );
    foreach ($metas as $meta)
    {
      if ($meta->getAttribute('name'))
      {
        $url_info[$meta->getAttribute('name')] = $meta->getAttribute('content');
      }
    }
    return $url_info;
  }
  /**
   *
   * Alexa rank
   * @param string $url
   * @return integer
   */
  public static function alexa_rank($url)
  {
    $domain   = self::domain_name($url);
    $request   = "http://data.alexa.com/data?cli=10&dat=s&url=" . $domain;
    $data     = self::get_html($request);
    preg_match('/<POPULARITY URL="(.*?)" TEXT="([\d]+)"\/>/si', $data, $p);
    return ($l[2]) ? $l[2] : NULL;
  }
  /**
   *
   * Alexa inbounds link
   * @param string $url
   * @return integer
   */
  public static function alexa_links($url)
  {
    $domain   = self::domain_name($url);
    $request   = "http://data.alexa.com/data?cli=10&dat=s&url=" . $domain;
    $data     = self::get_html($request);
    preg_match('/<LINKSIN NUM="([\d]+)"\/>/si', $data, $l);
    return ($l[1]) ? $l[1] : NULL;
  }
  /**
   * Returns total amount of results for any Google search,
   * requesting the deprecated Websearch API.
   *
   * @param    string    $query   String, containing the search query.
   * @return    integer          Returns a total count.
   */
  public static function google_pages($url)
  {
    //$query = self::domain_name($url);
    $url = 'http://ajax.googleapis.com/ajax/services/search/web?v=1.0&rsz=1&q='.$url;
    $str = self::get_html($url);
    $data = json_decode($str);
    return (!isset($data->responseData->cursor->estimatedResultCount))
        ? '0'
        : intval($data->responseData->cursor->estimatedResultCount);
  }
  /**
   *
   * gets the inbounds links from a site
   * @param string $url
   * @param integer
   */
  public static function google_links($url)
  {
    $request   = "http://www.google.com/search?q=" . urlencode("link:" . $url) . "&hl=en";
    $data     = self::get_html($request);
    preg_match('/<div id=resultStats>(About )?([\d,]+) result/si', $data, $l);
    return ($l[2]) ? $l[2] : NULL;
  }
  /**
   *
   * web of trust rating
   * @param string $url
   * @reutn integer
   */
  public static function WOT_rating($url)
  {
    $domain = self::domain_name($url);
    $request = "http://api.mywot.com/0.4/public_query2?target=" . $domain;
    $data   = self::get_html($request);
    preg_match_all('/<application name="(\d+)" r="(\d+)" c="(\d+)"\/>/si', $data, $regs);
    $trustworthiness = ($regs[2][0]) ? $regs[2][0] : NULL;
    return (is_numeric($trustworthiness))? $trustworthiness:NULL;
  }
   
  /**
   *
   * how old is the domain?
   * @param string $domain
   * @return integer unixtime
   */
  public static function domain_age($domain)
  {
    $request = "http://reports.internic.net/cgi/whois?whois_nic=" . $domain . "&type=domain";
    $data   = self::get_html($request);
    preg_match('/Creation Date: ([a-z0-9-]+)/si', $data, $p);
    return (!$p[1])?FALSE:strtotime($p[1]);
  }
  /**
   *
   * counts how many tweets about the url
   * @param string $url
   * @return integer
   */
  public static function tweet_count($url)
  {
    $url = urlencode($url);
    $twitterEndpoint = "http://urls.api.twitter.com/1/urls/count.json?url=%s";
    $fileData = file_get_contents(sprintf($twitterEndpoint, $url));
    $json = json_decode($fileData, true);
    unset($fileData);        // free memory
    return (is_numeric($json['count']))? $json['count']:NULL;
  }
  /**
   * Returns the total amount of Facebook Shares for a single page
   *
   * @link     https://graph.facebook.com/
   * @param     string   The URL to check.
   * @return    integer  Returns the total amount of Facebook
   */
  public static function facebook_shares($q)
  {
    //Execution and result of Json
    $str = self::get_html('http://graph.facebook.com/?id='.urlencode($q));
    $data = json_decode($str);
    //Return only number of facebook shares
    $r = $data->shares;
    return ($r != NULL) ? $r : intval('0');
  }
  /**
   *
   * get the pagespeed rank over 100
   * @param string $url
   * @return integer
   */
  public static function page_speed($url)
  {
    $url = 'https://developers.google.com/_apps/pagespeed/run_pagespeed?url='.$url.'&format=json';
    $str = self::get_html($url);
    $data = json_decode($str);
    return intval($data->results->score);
  }
  /**
   *
   * get google page rank
   * @param string $url
   * @return integer
   */
  public static function page_rank($url)
  {
     $query = "http://toolbarqueries.google.com/tbr?client=navclient-auto&ch=".self::CheckHash(self::HashURL($url)). "&features=Rank&q=info:".$url."&num=100&filter=0";
      $data = self::get_html($query);//die(print_r($data));
    $pos  = strpos($data, "Rank_");
    if($pos === false)
    {
      return NULL;
    }
    else
    {
      $pagerank = substr($data, $pos + 9);
      return $pagerank;
    }
  }
  // functions for google pagerank
  /**
   * To calculate PR functions
   */
  public static function StrToNum($Str, $Check, $Magic)
  {
    $Int32Unit = 4294967296; // 2^32
    $length = strlen($Str);
    for ($i = 0; $i < $length; $i++) {
      $Check *= $Magic;
      //If the float is beyond the boundaries of integer (usually +/- 2.15e+9 = 2^31),
      // the result of converting to integer is undefined
      // refer to http://www.php.net/manual/en/language.types.integer.php
      if ($Check >= $Int32Unit) {
        $Check = ($Check - $Int32Unit * (int) ($Check / $Int32Unit));
        //if the check less than -2^31
        $Check = ($Check < -2147483648) ? ($Check + $Int32Unit) : $Check;
      }
      $Check += ord($Str{$i});
    }
    return $Check;
  }
  /**
   * Genearate a hash for a url
   */
  public static function HashURL($String)
  {
    $Check1 = self::StrToNum($String, 0x1505, 0x21);
    $Check2 = self::StrToNum($String, 0, 0x1003F);
    $Check1 >>= 2;
    $Check1 = (($Check1 >> 4) & 0x3FFFFC0 ) | ($Check1 & 0x3F);
    $Check1 = (($Check1 >> 4) & 0x3FFC00 ) | ($Check1 & 0x3FF);
    $Check1 = (($Check1 >> 4) & 0x3C000 ) | ($Check1 & 0x3FFF);
    $T1 = (((($Check1 & 0x3C0) << 4) | ($Check1 & 0x3C)) <<2 ) | ($Check2 & 0xF0F );
    $T2 = (((($Check1 & 0xFFFFC000) << 4) | ($Check1 & 0x3C00)) << 0xA) | ($Check2 & 0xF0F0000 );
    return ($T1 | $T2);
  }
  /**
   * genearate a checksum for the hash string
   */
  public static function CheckHash($Hashnum)
  {
    $CheckByte = 0;
    $Flag = 0;
    $HashStr = sprintf('%u', $Hashnum) ;
    $length = strlen($HashStr);
    for ($i = $length - 1; $i >= 0; $i --) {
      $Re = $HashStr{$i};
      if (1 === ($Flag % 2)) {
        $Re += $Re;
        $Re = (int)($Re / 10) + ($Re % 10);
      }
      $CheckByte += $Re;
      $Flag ++;
    }
    $CheckByte %= 10;
    if (0 !== $CheckByte) {
      $CheckByte = 10 - $CheckByte;
      if (1 === ($Flag % 2) ) {
        if (1 === ($CheckByte % 2)) {
          $CheckByte += 9;
        }
        $CheckByte >>= 1;
      }
    }
    return '7'.$CheckByte.$HashStr;
  }
}

使用范例

<?php
include 'seoreport.php';
ini_set('max_execution_time', 180);
  $url = (isset($_GET['url']))?$_GET['url']:'http://phpclasses.org';
  $meta_tags = seoreport::meta_info($url);
  //die(var_dump($meta_tags));
  //first check if site online
  if ($meta_tags!==FALSE)
  {
    $stats = array();
    $stats['meta'] = $meta_tags;
    $stats['alexa']['rank'] = seoreport::alexa_rank($url);
    $stats['alexa']['links'] = seoreport::alexa_links($url);
    $stats['domain']['WOT_rating'] = seoreport::WOT_rating($url);  
    $stats['domain']['domain_age'] = seoreport::domain_age($url);  
    $stats['social']['twitter'] = seoreport::tweet_count($url);  
    $stats['social']['facebook'] = seoreport::facebook_shares($url);
    $stats['google']['page_rank'] = seoreport::page_rank($url);
    $stats['google']['page_speed'] = seoreport::page_speed($url);
    $stats['google']['pages'] = seoreport::google_pages($url);
    $stats['google']['links'] = seoreport::google_links($url);
    var_dump($stats);
  }
  else 'Site not online. '.$url;

希望本文所述对大家的php程序设计有所帮助。

PHP 相关文章推荐
使用php4加速网络传输
Oct 09 PHP
PHP include_path设置技巧分享
Jul 03 PHP
浏览器关闭后,能继续执行的php函数(ignore_user_abort)
Aug 01 PHP
php引用传值实例详解学习
Nov 06 PHP
从零开始学YII2框架(六)高级应用程序模板
Aug 20 PHP
php实现在多维数组中查找特定value的方法
Jul 29 PHP
Symfony学习十分钟入门经典教程
Feb 03 PHP
php实现有序数组打印或排序的方法【附Python、C及Go语言实现代码】
Nov 10 PHP
php修改数组键名的方法示例
Apr 15 PHP
解决安装WampServer时提示缺少msvcr110.dll文件的问题
Jul 09 PHP
[原创]PHP正则匹配中英文、数字及下划线的方法【用户名验证】
Aug 01 PHP
PHP获取星期几的常用方法小结
Dec 18 PHP
php获得网站访问统计信息类Compete API用法实例
Apr 02 #PHP
php实现从上传文件创建缩略图的方法
Apr 02 #PHP
php调用KyotoTycoon简单实例
Apr 02 #PHP
PHP中数据类型转换的三种方式
Apr 02 #PHP
php在apache环境下实现gzip配置方法
Apr 02 #PHP
PHP中使用socket方式GET、POST数据实例
Apr 02 #PHP
php获取百度收录、百度热词及百度快照的方法
Apr 02 #PHP
You might like
php ZipArchive压缩函数详解实例
2013/11/06 PHP
PHP SPL标准库之SplFixedArray使用实例
2015/05/12 PHP
Yii使用Captcha验证码的方法
2015/12/28 PHP
关于laravel模板中生成URL的几种模式总结
2019/10/18 PHP
PHP var关键字相关原理及使用实例解析
2020/07/11 PHP
parseInt parseFloat js字符串转换数字
2010/08/01 Javascript
jQuery中:selected选择器用法实例
2015/01/04 Javascript
jquery动态添加删除(tr/td)
2015/02/09 Javascript
解决jquery中动态新增的元素节点无法触发事件问题的两种方法
2015/10/30 Javascript
Angular2 PrimeNG分页模块学习
2017/01/14 Javascript
vue2.0项目中使用Ueditor富文本编辑器示例代码
2017/08/14 Javascript
jQuery插件DataTables分页开发心得体会
2017/08/22 jQuery
Angular弹出模态框的两种方式
2017/10/19 Javascript
bootstrap动态调用select下拉框的实例代码
2018/08/09 Javascript
vue 指令和过滤器的基本使用(品牌管理案例)
2019/11/04 Javascript
微信小程序实现组件顶端固定或底端固定效果(不随滚动而滚动)
2020/04/09 Javascript
Vue中的this.$options.data()和this.$data用法说明
2020/07/26 Javascript
使用js获取身份证年龄的示例代码
2020/12/11 Javascript
Python简单实现子网掩码转换的方法
2016/04/13 Python
python实现批量监控网站
2016/09/09 Python
基于python内置函数与匿名函数详解
2018/01/09 Python
利用python-docx模块写批量生日邀请函
2019/08/26 Python
python3下pygame如何实现显示中文
2020/01/11 Python
pycharm专业版远程登录服务器的详细教程
2020/09/15 Python
五分钟学会怎么用python做一个简单的贪吃蛇
2021/01/12 Python
新媒传信软件测试面试题
2013/02/24 面试题
幼儿园庆六一游园活动方案
2014/01/29 职场文书
小班上学期评语
2014/05/05 职场文书
应届生求职信范文
2014/05/26 职场文书
党员创先争优心得体会
2014/09/11 职场文书
2014教师个人自我评价范文
2014/09/13 职场文书
2014年教学管理工作总结
2014/12/02 职场文书
支教个人总结
2015/03/04 职场文书
解决golang 关于全局变量的坑
2021/05/06 Golang
【D4DJ】美少女DJ企划 动画将于明年冬季开播第2季
2022/04/11 日漫
清空 Oracle 安装记录并重新安装
2022/04/26 Oracle