常見問題

php 實(shí)現(xiàn)sitemap地圖生成xml格式-襄陽網(wǎng)站開發(fā)公司分享

常見問題

2576

字體:

使用php 實(shí)現(xiàn)sitemap地圖生成,帶頭過濾空鏈接去除等操作,拿到就可用使用,如果需要循環(huán)子頁面可寫循環(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);

// 獲取頁面鏈接地址
        $url = 'http://donedealhomebuyer.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();


[聲明]原創(chuàng)不易,請(qǐng)轉(zhuǎn)發(fā)者備注下文章來源(hbsjsd.cn)【速建時(shí)代】。