php往sitemap.xml中写数据
时间: 2023-12-15 19:06:08 浏览: 36
要将数据写入sitemap.xml文件中,您可以使用PHP的DOMDocument类来创建XML文档并将其写入文件中。以下是一个示例代码,演示如何创建一个sitemap.xml文件并向其中添加一些数据:
```
<?php
// 创建一个新的DOMDocument对象
$xmlDoc = new DOMDocument('1.0', 'UTF-8');
// 创建根元素<urlset>并将其添加到文档中
$urlset = $xmlDoc->createElement('urlset');
$urlset->setAttribute('xmlns', 'http://www.sitemaps.org/schemas/sitemap/0.9');
$xmlDoc->appendChild($urlset);
// 创建一个新的<url>元素并将其添加到<urlset>中
$url = $xmlDoc->createElement('url');
$urlset->appendChild($url);
// 添加<loc>元素和其文本节点
$loc = $xmlDoc->createElement('loc', 'https://www.example.com');
$url->appendChild($loc);
// 添加<lastmod>元素和其文本节点
$lastmod = $xmlDoc->createElement('lastmod', date('Y-m-d'));
$url->appendChild($lastmod);
// 将XML文档保存到文件中
$xmlDoc->formatOutput = true;
$xmlDoc->save('sitemap.xml');
?>
```
上述代码将创建一个包含一个URL的sitemap.xml文件。您可以根据需要添加更多的URL元素。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)