襄阳做网站,襄阳网站设计,襄阳网站开发,微信小程序开发,网站设计制作,专业建站公司

当前位置:

php 实现sitemap地图生成xml格式-襄阳网站开发公司分享

常见问题

1750

文章来源(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)【速建时代】。

速建时代高端网站定制开发回到顶部
站内SEO关键词搜索