php 實(shí)現(xiàn)sitemap地圖生成xml格式-襄陽(yáng)網(wǎng)站開發(fā)公司分享
使用php 實(shí)現(xiàn)sitemap地圖生成,帶頭過(guò)濾空鏈接去除等操作,拿到就可用使用,如果需要循環(huán)子頁(yè)面可寫循環(huán)即可使用,
use DOMDocument;
use DOMXPath;
// 創(chuàng)建 XML 文件
$xml = new DOMDocument('1.0', 'utf-8');
$xml->formatOutput = true;
// 創(chuàng)建根節(jié)點(diǎn)和 xmlns 屬性
$urlset = $xml->createElementNS('http://www.sitemaps.org/schemas/sitemap/0.9', 'urlset');
$urlset->setAttributeNS('http://www.w3.org/2000/xmlns/', 'xmlns:image', 'http://www.google.com/schemas/sitemap-image/1.1');
$xml->appendChild($urlset);
// 獲取頁(yè)面鏈接地址
$url = 'http://www.superbettingonline.com';
$html = file_get_contents($url);
$dom = new DOMDocument();
@$dom->loadHTML($html);
$xpath = new DOMXPath($dom);
$links = $xpath->query('//a/@href');
// 整理鏈接地址
$urls = array();
foreach ($links as $link) {
$href = $link->nodeValue;
$href=str_replace(' ', '', $href);
if ($href == 'javascript:void(0)' || $href == 'javascript:;' ){
continue;
}
$preg = "/^tel?:/";
if (preg_match($preg, $href)){
continue;
}
$preg = "/^http(s)?:\\/\\/.+/";
if(preg_match($preg,$href)){
continue;
}else{
$href=$url.$href;
}
// 去掉鏈接末尾的斜杠
$link = rtrim($href, '/');
// 去除重復(fù)鏈接
if (in_array($link, $urls)) {
continue;
}
$urls[] = $link;
}
// 添加鏈接地址到 XML 文件中
foreach ($urls as $url) {
$url_node = $xml->createElement('url');
$loc_node = $xml->createElement('loc', $url);
$url_node->appendChild($loc_node);
$urlset->appendChild($url_node);
}
// 輸出 XML 文件內(nèi)容
echo $xml->saveXML();
關(guān)鍵詞: phpsitemap生成
鄂公網(wǎng)安備42060002000147