首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 綜合知識

PHP 自動 Ping 百度收錄接口實現代碼

     編輯:PHP 綜合知識

使用場景

文章發布/更新時自動通知百度,加速收錄。返回 XML 中 <int>0</int> 表示成功。

調用示例

<?php
$pingUrl = 'https://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
$arcPing = new Ping('站點標題', $pingUrl, get_domain(), 'https://www.example.com/rss.xml');
$arcPing->pingBaidu();
?>

Ping 類完整代碼

<?php
class Ping {
    private $title, $hostUrl, $artUrl, $rssUrl, $baiduXml, $baiduRpc = 'https://ping.baidu.com/ping/RPC2';

    public function __construct($title, $artUrl, $hostUrl, $rssUrl) {
        if (empty($title) || empty($artUrl)) return false;
        $this->title = $title;
        $this->artUrl = $artUrl;
        $this->hostUrl = $hostUrl;
        $this->rssUrl = $rssUrl;

        $this->baiduXml = '<?xml version="1.0" encoding="UTF-8"?>';
        $this->baiduXml .= '<methodCall><methodName>weblogUpdates.extendedPing</methodName><params>';
        $this->baiduXml .= '<param><value><string>' . $this->hostUrl . '</string></value></param>';
        $this->baiduXml .= '<param><value><string>' . $this->title . '</string></value></param>';
        $this->baiduXml .= '<param><value><string>' . $this->artUrl . '</string></value></param>';
        $this->baiduXml .= '<param><value><string>' . $this->rssUrl . '</string></value></param>';
        $this->baiduXml .= '</params></methodCall>';
    }

    public function pingBaidu() {
        $ch = curl_init();
        curl_setopt_array($ch, [
            CURLOPT_URL => $this->baiduRpc,
            CURLOPT_HEADER => 1,
            CURLOPT_RETURNTRANSFER => 1,
            CURLOPT_POST => 1,
            CURLOPT_HTTPHEADER => [
                'User-Agent: request',
                'Host: ping.baidu.com',
                'Content-Type: text/xml',
            ],
            CURLOPT_POSTFIELDS => $this->baiduXml,
        ]);
        $res = curl_exec($ch);
        curl_close($ch);
        return strpos($res, '<int>0</int>') !== false;
    }
}

function get_domain() {
    $protocol = 'https://';
    if (isset($_SERVER['HTTP_X_FORWARDED_HOST'])) $host = $_SERVER['HTTP_X_FORWARDED_HOST'];
    elseif (isset($_SERVER['HTTP_HOST'])) $host = $_SERVER['HTTP_HOST'];
    else {
        $port = '';
        if (isset($_SERVER['SERVER_PORT'])) {
            $port = ':' . $_SERVER['SERVER_PORT'];
            if (($port === ':80' && $protocol === 'https://') || ($port === ':443' && $protocol === 'https://')) $port = '';
        }
        $host = (isset($_SERVER['SERVER_NAME']) ? $_SERVER['SERVER_NAME'] : $_SERVER['SERVER_ADDR']) . $port;
    }
    return $protocol . $host;
}
?>

優化建議

  • 使用 百度站長平台主動推送 API(需驗證站點獲取 Token),比 XML-RPC 更高效、實時。
  • 記錄 Ping 返回結果與時間,便於排查收錄異常。
  • 批量發布時合併推送,避免頻繁請求觸發限流。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved