您好我想在php中创建sitemap.xml表单数据库数据。
我目前的代码在下面我从数据库中获取数据。
$show_data = "query to database";
$rows = mysqli_query($conn, $show_data);
$row = mysqli_fetch_array($rows);
while($row = mysqli_fetch_array($rows)){
echo "<url>\n";
echo "<loc>https://example.com/page/".$row['id']."</loc>\n";
echo "<lastmod>".$date_show."</lastmod>\n";
echo "<changefreq>weekly</changefreq>\n";
echo "<priority>0.80</priority>\n";
echo "</url>\n";
}
答案 0 :(得分:0)
mysqli_result
实现Traversable
(PHP&gt; = 5.4),因此您可以直接在foreach
中使用它。将它与XMLWriter结合起来就完成了。
$targetFile = 'php://stdout';
$xmlns = 'http://www.sitemaps.org/schemas/sitemap/0.9';
$date = date('Y-m-d');
$writer = new XMLWriter();
$writer->openUri($targetFile);
$writer->setIndent(2);
$writer->startDocument();
$writer->startElementNS(NULL, 'urlset', $xmlns);
foreach ($queryResult as $row) {
$writer->startElement('url');
$writer->writeElement('loc', 'https://example.com/page/'.urlencode($row['id']));
$writer->writeElement('lastmod', $date);
$writer->writeElement('priority', '0.80');
$writer->endElement();
}
$writer->endElement();
$writer->endDocument();