如何在 php 中的 </urlset> 结束标记之前将字符串添加到 sitemap.xml

How to add string to sitemap.xml before </urlset> closing tag, in php

经过几个小时的寻找解决方案,我找不到任何有效或适合我的问题。

基本上,我有动态网站,它会生成新页面,我想为其添加将新页面添加到 sitemap.xml

的功能

当我使用:

file_put_contents("$sitemap_file", $string_to_add, FILE_APPEND);

它将在 sitemap.xml 的末尾添加 $string_to_add,在 /urlset 标记之后。

有什么方法可以在 /urlset 标签之前添加这个字符串吗?

我目前的代码:

$date_mod = date('Y-m-d');
$string = "
<url>
    <loc>https://www.mywebsite.com$internal_link</loc>
    <lastmod>$date_mod</lastmod>
    <changefreq>monthly</changefreq>
</url>";

file_put_contents("$root/sitemap.xml", $string, FILE_APPEND);

您可以使用 SimpleXML:

尝试如下操作
$date_mod = date('Y-m-d');
$string = "
<url>
    <loc>https://www.mywebsite.com$internal_link</loc>
    <lastmod>$date_mod</lastmod>
    <changefreq>monthly</changefreq>
</url>";


$xml = simplexml_load_file("$root/sitemap.xml");
$xml->addChild($string);

file_put_contents("$root/sitemap.xml", $xml->asXML());

希望这会将 <url> 放入 <urlset> 标签中。

只需使用 SimpleXML:

// You can also do
// $xmlStr= file_get_contents('sitemap.xml');
$xmlStr=<<<XML
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
<url>
<loc>http://domain.fake/link1.html</loc>
<priority>1.0</priority>
</url>
<url>
<loc>http://domain.fake/link2.html</loc>
<priority>0.99</priority>
</url>
</urlset>
XML;

// Create the SimpleXML object from the string
$xml = simplexml_load_string($xmlStr);
// add an <url> child to the <urlset> node
$url = $xml->addChild("url");
// add the <loc> and <priority> children to the <url> node 
$url->addChild("loc", "http://domain.fake/link2.html");
$url->addChild("priority", 0.98);

// get the updated XML string
$newXMLStr = $xml->asXML();
//write it to the sitemap.xml file
file_put_contents('sitemap.xml',$newXMLStr);