文章来源(hbsjsd.cn)湖北高端网站定制开发公司-速建时代
使用php 实现sitemap地图生成,带头过滤空链接去除等操作,拿到就可用使用,如果需要循环子页面可写循环即可使用,
use DOMDocument; use DOMXPath; // 创建 XML 文件 $xml = new DOMDocument('1.0', 'utf-8'); $xml->formatOutput = true; // 创建根节点和 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); // 获取页面链接地址 $url = 'https://www.hbsjsd.cn'; $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, '/'); // 去除重复链接 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 文件内容 echo $xml->saveXML();
[声明]原创不易,请转发者备注下文章来源(hbsjsd.cn)【速建时代】。