话不多说,直接上代码!
<?php
/*Template Name: xml页面模板*/?><?php //php DOM 生成xml$doc = new DOMDocument('1.0','utf-8');//声明版本和编码$doc -> formatOutput = true;//格式xml输出 有换行什么的$urlset = $doc -> createElement('urlset');//根标签foreach($wpdb->get_results("select * from wp_posts where post_status='publish' and post_type='post' order by post_date DESC") as $val ){
$date = substr($val->post_date,0,10); $link = get_permalink($val->ID); //echo "<pre>";print_r($date.$link);$url = $doc -> createElement('url');//加标签
//四个小标签 $loc = $doc -> createElement('loc'); $lastmod = $doc -> createElement('lastmod'); $changefreq = $doc -> createElement('changefreq'); $priority = $doc -> createElement('priority'); //设置内容 $locContent = $doc -> createTextNode($link);//链接内容 $lastmodContent = $doc -> createTextNode($date);//更新时间 $changefreqContent = $doc -> createTextNode('weekly'); //设置内容 $priorityContent = $doc -> createTextNode('0.8'); //设置内容$xx = $doc -> createTextNode('http://www.w3.org/2001/XMLSchema-instance'); //设置内容
$ns = $doc -> createTextNode('http://www.sitemaps.org/schemas/sitemap/0.9'); //设置内容 $xsi = $doc -> createTextNode('http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd'); //设置内容//根标签设置属性
$xmlnsxsi = $doc -> createAttribute('xmlns:xsi'); $xmlns = $doc -> createAttribute('xmlns'); $schemaLocation = $doc -> createAttribute('xsi:schemaLocation'); $xmlnsxsi -> appendChild($xx);//属性内容赋值给属性 $xmlns -> appendChild($ns);//属性内容赋值给属性 $schemaLocation -> appendChild($xsi);//属性内容赋值给属性 //设置所属关系$urlset -> appendChild($xmlnsxsi);
$urlset -> appendChild($xmlns); $urlset -> appendChild($schemaLocation);$changefreq -> appendChild($changefreqContent);//内容
$priority -> appendChild($priorityContent);//内容 $loc -> appendChild($locContent);//内容 $lastmod -> appendChild($lastmodContent);//内容$url -> appendChild($loc);
$url -> appendChild($lastmod);$url -> appendChild($changefreq);
$url -> appendChild($priority); $urlset -> appendChild($url);//url为二级标签 };$doc -> appendChild($urlset);//把urlset标签作为根标签 $doc -> save('sitemap.xml');//保存生成xml文件//$time = date('Y-m-d H:i:s',time());//echo $doc?'成功'.$time:'失败'.$time;header("Location: http://ai_10_1.cn/sitemap.xml");
?>
亲测有效,看个人需求修改,具体来源忘记了,反正看了挺多的文章,自己也总结了下。