百度權重是站長評估網站流量潛力的常用指標。愛站網與站長工具各有獨立算法,本文提供兩個 PHP 函式分別串接其非官方 API 獲取權重值,並說明使用限制與替代方案。
<?php
/**
* 取得愛站網百度權重
* @param string $domain 完整域名,如 www.example.com
* @return int 權重值 0-10,失敗回傳 0
*/
function getAizhanBaiduWeight($domain) {
$url = "https://www.aizhan.com/getbr.php?url=" . urlencode($domain) . "&style=1";
$ctx = stream_context_create([
'http' => [
'timeout' => 5,
'header' => "User-Agent: Mozilla/5.0 (compatible; PHP Bot)\r\n"
]
]);
$content = @file_get_contents($url, false, $ctx);
if ($content === false) return 0;
// 回傳格式通常為純數字或簡單 HTML 片段
if (preg_match('/\b([0-9]|10)\b/', $content, $m)) {
return (int)$m[1];
}
return 0;
}
// 使用範例
echo getAizhanBaiduWeight('www.baidu.com'); // 輸出如 9
?>
<?php
/**
* 取得站長工具百度權重
* @param string $domain 域名
* @return int 權重值 0-10,失敗回傳 0
*/
function getChinazBaiduWeight($domain) {
$url = "https://mytool.chinaz.com/baidusort.aspx?host=" . urlencode($domain);
$ctx = stream_context_create([
'http' => [
'timeout' => 8,
'header' => "User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36\r\n"
]
]);
$html = @file_get_contents($url, false, $ctx);
if ($html === false) return 0;
// 頁面結構可能變動,需定期維護選擇器
// 典型特徵:9 或類似
if (preg_match('/class=["\']br["\'][^>]*>\s*([0-9]|10)\s*
<?php
class BaiduWeightFetcher {
private $cacheDir;
private $ttl = 3600; // 1 小時快取
public function __construct($cacheDir = __DIR__ . '/cache') {
$this->cacheDir = $cacheDir;
if (!is_dir($cacheDir)) mkdir($cacheDir, 0755, true);
}
public function getWeight($domain, $source = 'aizhan') {
$cacheFile = $this->cacheDir . '/' . md5($domain . '_' . $source) . '.json';
// 讀取快取
if (file_exists($cacheFile) && (time() - filemtime($cacheFile) < $this->ttl)) {
$data = json_decode(file_get_contents($cacheFile), true);
if ($data) return $data['weight'];
}
$weight = 0;
try {
if ($source === 'aizhan') $weight = $this->fetchAizhan($domain);
elseif ($source === 'chinaz') $weight = $this->fetchChinaz($domain);
} catch (Exception $e) {
error_log("BaiduWeightFetcher error: " . $e->getMessage());
}
// 寫入快取
file_put_contents($cacheFile, json_encode(['weight' => $weight, 'time' => time()]));
return $weight;
}
private function fetchAizhan($domain) {
$url = "https://www.aizhan.com/getbr.php?url=" . urlencode($domain) . "&style=1";
$content = $this->httpGet($url);
return preg_match('/\b([0-9]|10)\b/', $content) ? (int)$m[1] : 0;
}
private function fetchChinaz($domain) {
$url = "https://mytool.chinaz.com/baidusort.aspx?host=" . urlencode($domain);
$html = $this->httpGet($url);
if (preg_match('/class=["\']br["\'][^>]*>\s*([0-9]|10)\s* ['timeout' => 10, 'header' => "User-Agent: Mozilla/5.0\r\n"]
]);
return @file_get_contents($url, false, $ctx) ?: '';
}
}
// 使用
$fetcher = new BaiduWeightFetcher();
echo "愛站權重: " . $fetcher->getWeight('www.example.com', 'aizhan') . "\n";
echo "站長權重: " . $fetcher->getWeight('www.example.com', 'chinaz') . "\n";
?>
robots.txt 及服務條款。