I am using PHP to dynamically generate an XML sitemap. The generation part is running smooth but am somehow unable to save the results as an XML file. Here's the PHP I wrote:
$xml = new SimpleXMLElement('<?xml version="1.0" encoding="utf-8" ?><urlset xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:image="http://www.google.com/schemas/sitemap-image/1.1" xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd"/>');
$node = $xml->addChild('url');
$node->addChild('loc', 'http://www.pb.com/blog/');
$node->addChild('changefreq', "daily");
$node->addChild('priority', "1");
$connect = dbconn(PROJHOST, POSTSDB, POSTSUSR, POSTSPWD);
$sql = "SELECT * FROM tblposts ORDER BY id";
$query = $connect->prepare($sql);
if($query->execute()) {
$rows = $query->fetchAll(PDO::FETCH_ASSOC);
if($rows){
foreach($rows as $row){
$post_date = $row['post_date'];
$node = $xml->addChild('url');
$node->addChild('loc', trim("http://www.pb.com/blog/" . $row['post_name']));
$node->addChild('lastmod', str_replace(' ', 'T', $row['post_date']) . "-05:00");
$node->addChild('changefreq', "weekly");
$node->addChild('priority', "0.6");
}
}
}
Header('Content-type: text/xml');
print($xml->asXML());
// $dom->preserveWhiteSpace = FALSE;
$xml->save('sitemap.xml');
The fatal error it's throwing is:
Call to undefined method SimpleXMLElement::save() in /xxx/xxx/xxx/sandboxgenerate_sitemap.php on line 79
Any alternative?
The SimpleXMLElement class does not have a method called save(). Instead use asXML(), like you did in the line above, and pass it the optional $filename parameter. Specifying this parameter will result in the XML being saved to the file rather than displayed. Further documentation here: http://php.net/manual/en/simplexmlelement.asxml.php