有些网站会自动生成sitemap.xml文件,这样我们就不用手动去更新url链接了,只需要一个函数读取sitemap.xml文件,然后就可以一键提交到百度站长了。

代码

我们使用PHP自带的simplexml_load_file函数来读取sitemap.xml文件,使用curl把这些链接提交到百度站长。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
$site = "网站地址";
$token = "百度站长token";
$xml = simplexml_load_file('sitemap.xml');
$urls = array();
foreach ($xml->url as $url) {
$urls[] = $url->loc;
}
if(count($urls) > 0){
$api = "http://data.zz.baidu.com/urls?site=$site&token=$token";
$ch = curl_init();
$options = array(
CURLOPT_URL => $api,
CURLOPT_POST => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POSTFIELDS => implode("\n", $urls),
CURLOPT_HTTPHEADER => array('Content-Type: text/plain'),
);
curl_setopt_array($ch, $options);
$result = curl_exec($ch);
curl_close($ch);
$success = json_decode($result)->success;
if($success){
echo "推送成功";
}
else{
echo "推送失败";
}
}

整体实现起来相对简单,读取完成之后自动生成了一个数组,就可以直接用在curl的提交上了。