>  기사  >  백엔드 개발  >  컬을 사용하여 PHP에서 Compete 통계 웹사이트 정보를 얻는 방법

컬을 사용하여 PHP에서 Compete 통계 웹사이트 정보를 얻는 방법

墨辰丷
墨辰丷원래의
2018-06-11 17:26:091361검색

이 글은 주로 PHP에서 Compete API를 사용하여 웹사이트 액세스 통계를 얻는 방법을 소개합니다. PHP에서 Compete 통계 웹사이트 정보를 얻기 위해 컬을 사용하는 기술을 분석합니다.

이 문서의 예에서는 PHP가 웹 사이트 액세스 통계 클래스 Compete API 사용을 얻는 방법을 설명합니다. 자세한 내용은 다음과 같습니다.

여기에서는 PHP를 사용하여 웹 사이트 액세스 통계를 얻습니다. Compete API는 웹 사이트 정보를 계산하는 데 특별히 사용되는 웹 사이트입니다.

<?php
// Check for dependencies
if (!function_exists(&#39;curl_init&#39;))
 throw new Exception(&#39;Compete needs the CURL PHP extension.&#39;);
if (!function_exists(&#39;json_decode&#39;))
 throw new Exception(&#39;Compete needs the JSON PHP extension.&#39;);
/**
 * Base Compete exception class.
 */
class CompeteException extends Exception {}
/**
 * Represents Compete API.
 * @author Egor Gumenyuk (boo1ean0807 at gmail dot com)
 * @package Compete
 * @license Apache 2.0
 */
class Compete
{
 /**
  * Default usr agent.
  */
 const USER_AGENT  = &#39;Compete API wrapper for PHP&#39;;
 /**
  * Base url for api calls.
  */
 const API_BASE_URL = &#39;http://apps.compete.com/sites/:domain/trended/:metric/?apikey=:key&#39;;
 /**
  * Masks for url params.
  */
 private $_urlKeys = array(&#39;:domain&#39;, &#39;:metric&#39;, &#39;:key&#39;);
 private $_apiKey;
 /**
  * For url cleaning.
  */
 private $_toSearch = array(&#39;http://&#39;, &#39;www.&#39;);
 private $_toReplace = array(&#39;&#39;, &#39;&#39;);
 /**
  * List of available metrics.
  */
 private $_availableMetrics = array(
       // Description   Auth type
  &#39;uv&#39;,   // Unique Visitors Basic
  &#39;vis&#39;,  // Visits      Basic
  &#39;rank&#39;,  // Rank       Basic
  &#39;pv&#39;,   // Page Views    All-Access
  &#39;avgstay&#39;,// Average Stay   All-Access
  &#39;vpp&#39;,  // Visits/Person  All-Access
  &#39;ppv&#39;,  // Pages/Visit   All-Access
  &#39;att&#39;,  // Attention    All-Access
  &#39;reachd&#39;, // Daily Reach   All-Access
  &#39;attd&#39;,  // Daily Attention All-Access
  &#39;gen&#39;,  // Gender      All-Access
  &#39;age&#39;,  // Age       All-Access
  &#39;inc&#39;,  // Income      All-Access
 );
 /**
  * List of available methods for __call() implementation.
  */
 private $_metrics = array(
  &#39;uniqueVisitors&#39; => &#39;uv&#39;,
  &#39;visits&#39;     => &#39;vis&#39;,
  &#39;rank&#39;      => &#39;rank&#39;,
  &#39;pageViews&#39;   => &#39;pv&#39;,
  &#39;averageStay&#39;  => &#39;avgstay&#39;,
  &#39;visitsPerson&#39;  => &#39;vpp&#39;,
  &#39;pagesVisit&#39;   => &#39;ppv&#39;,
  &#39;attention&#39;   => &#39;att&#39;,
  &#39;dailyReach&#39;   => &#39;reachd&#39;,
  &#39;dailyAttention&#39; => &#39;attd&#39;,
  &#39;gender&#39;     => &#39;gen&#39;,
  &#39;age&#39;      => &#39;age&#39;,
  &#39;income&#39;     => &#39;inc&#39;
 );
 /**
  * Create access to Compete API.
  * @param string $apiKey user&#39;s api key.
  */
 public function __construct($apiKey) {
  $this->_apiKey = $apiKey;
 }
 /**
  * Implement specific methods.
  */
 public function __call($name, $args) {
  if (array_key_exists($name, $this->_metrics) && isset($args[0]))
   return $this->get($args[0], $this->_metrics[$name]);
  throw new CompeteException($name . &#39; method does not exist.&#39;);
 }
 /**
  * Get data from Compete.
  * @param string $site some domain.
  * @param string $metric metric to get.
  * @return stdClass Compete data.
  * @throws CompeteException
  */
 public function get($site, $metric) {
  if (!in_array($metric, $this->_availableMetrics))
   throw new CompeteException($metric . &#39; - wrong metric.&#39;);
  $values = array(
   $this->_prepareUrl($site),
   $metric,
   $this->_apiKey
  );
  // Prepare call url
  $url = str_replace($this->_urlKeys, $values, self::API_BASE_URL);
  // Retrieve data using HTTP GET method.
  $data = json_decode($this->_get($url));
  // Because of unsuccessful responses contain "status_message".
  if (!isset($data->status_message))
   return $data;
  throw new CompeteException(&#39;Status: &#39; . $data->status . &#39;. &#39; .$data->status_message);
 }
 /**
  * Cut unnecessary parts of url.
  * @param string $url some url.
  * @return string trimmed url.
  */
 private function _prepareUrl($url) {
  return str_replace($this->_toSearch, $this->_toReplace, $url);
 }
 /**
  * Execute http get method.
  * @param string $url request url.
  * @return string response.
  */
 private function _get($url) {
  $ch = curl_init();
  curl_setopt($ch, CURLOPT_URL, $url);
  curl_setopt($ch, CURLOPT_USERAGENT, self::USER_AGENT);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  return curl_exec($ch);
 }
}

요약: 위 내용이 이 기사의 전체 내용입니다. 모든 사람이 도움말을 배우는 데 도움이 될 수 있습니다.

관련 권장 사항:

PHP는 컬을 사용하여 게시물을 보내고, 요청을 받고, 쿠키를 작동합니다.

php 함수를 사용하여 Sina 음악 라이브러리 검색 인터페이스를 통해 노래를 쿼리합니다.

php 메서드를 사용하여 폴더와 파일을 동적으로 생성합니다. 업로드

위 내용은 컬을 사용하여 PHP에서 Compete 통계 웹사이트 정보를 얻는 방법의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.