Reputation: 17
I tried to add a string into the sitemap.xml file inside <urlset>
tag, but it stores differently.
<?php
$date_mod = date('Y-m-d');
$sitemap = "<url>
<loc>http://www.website.com/article.php?page=3</loc>
<lastmod>$date_mod</lastmod>
<priority>0</priority>
</url>";
$xml = simplexml_load_file("sitemap.xml");
$xml->addChild($sitemap);
file_put_contents("sitemap.xml", $xml->asXML());
?>
The output is like:
<?xml version="1.0"?>
<urlset>
<url>
<loc>http://www.website.com/article.php?page=3</loc>
<lastmod>2018-01-12</lastmod>
<priority>0</priority>
</url>
<//www.website.com/article.php?page=3</loc>
<lastmod>2018-01-12</lastmod>
<priority>0</priority>
</url>/></urlset>
Please help me.
Upvotes: 1
Views: 204
Reputation: 1464
If the raw xml is like this:
<?xml version="1.0"?>
<urlset>
</urlset>
And you updated xml is like this:
<?xml version="1.0"?>
<urlset>
<url>
<loc>http://www.website.com/article.php?page=3</loc>
<lastmod>2018-01-12</lastmod>
<priority>0</priority>
</url>
</urlset>
Then you could refer to the following code:
<?php
$date_mod = date('Y-m-d');
$sitemap = "<url>
<loc>http://www.website.com/article.php?page=3</loc>
<lastmod>$date_mod</lastmod>
<priority>0</priority>
</url>";
$sitemap_node =simplexml_load_string($sitemap);
$xml = simplexml_load_file("sitemap.xml");
sxml_append($xml,$sitemap_node);
$xml->asXML('sitemap.xml');
function sxml_append(SimpleXMLElement $to, SimpleXMLElement $from) {
$toDom = dom_import_simplexml($to);
$fromDom = dom_import_simplexml($from);
$toDom->appendChild($toDom->ownerDocument->importNode($fromDom, true));
}
?>
Your previous code failed to do that is because addChild
method can only deal with text (and stil has some drawbacks), not another xml object.
Upvotes: 1