【问题标题】:Unable to save dynamically generated XML sitemap using PHP [duplicate]无法使用 PHP 保存动态生成的 XML 站点地图 [重复]
【发布时间】:2017-01-24 14:23:52
【问题描述】:

我正在使用 PHP 来动态生成 XML 站点地图。生成部分运行顺利,但不知何故无法将结果保存为 XML 文件。这是我写的 PHP:

$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');

它抛出的致命错误是:

调用未定义的方法 SimpleXMLElement::save() in /xxx/xxx/xxx/sandboxgenerate_sitemap.php 在第 79 行

还有其他选择吗?

【问题讨论】:

标签: php xml simplexml


【解决方案1】:

SimpleXMLElement 类没有称为 save() 的方法。而是使用 asXML(),就像您在上面的行中所做的那样,并将可选的 $filename 参数传递给它。指定此参数将导致 XML 被保存到文件中而不是显示。更多文档在这里:http://php.net/manual/en/simplexmlelement.asxml.php

【讨论】:

    【解决方案2】:

    http://php.net/manual/de/class.simplexmlelement.php 列出了方法,如果你想创建一个文件,我认为$xml-&gt;asXML('sitemap.xml') 可以完成这项工作。

    【讨论】:

      猜你喜欢
      • 2012-10-17
      • 2017-11-29
      • 2019-06-22
      • 1970-01-01
      • 2011-03-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多