wordpress生成xml

话不多说,直接上代码!

<?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");

 ?>

 

 亲测有效,看个人需求修改,具体来源忘记了,反正看了挺多的文章,自己也总结了下。

转载于:https://www.cnblogs.com/shenmu/p/9810646.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值