【问题标题】:PHP DOMDocument - how to add Namespace declaration?PHP DOMDocument - 如何添加命名空间声明?
【发布时间】:2018-02-11 10:53:26
【问题描述】:

我正在根据以下代码创建一个动态的sitemap.xml

 <?php

 $dom = new DOMDocument();

 $dom->encoding = 'utf-8';
 $dom->xmlVersion = '1.0';
 $dom->formatOutput = true;

 $xml_file_name = 'SM_listings'.$mid.'.xml';

 $root = $dom->createElement('urlset');


     while(!$listings->atEnd()) {
         $url_node = $dom->createElement('url');
         $child_node_loc = $dom->createElement('loc', urlTarget.$listings->getColumnVal('invId'));
    $url_node->appendChild($child_node_loc);

    $child_node_date = $dom->createElement('lastmod', $listings->getColumnVal('Submit_date'));
    $url_node->appendChild($child_node_date);
  $root->appendChild($url_node);


 $listings->moveNext();
                            }
 $listings->moveFirst(); //return RS to first record


 $dom->appendChild($root);
 $dom->save($xml_file_name);

 echo "$xml_file_name has been successfully created";

 ?>

这可行,但 Google 不高兴“urlset”节点中没有命名空间声明。 Google 错误:“您的站点地图或站点地图索引文件未声明预期的命名空间:http://www.sitemaps.org/schemas/sitemap/0.9

如果我将代码更改为:

$root = $dom->createElement('urlset 
xmlns=“http://www.sitemaps.org/schemas/sitemap/0.9"');

生成xml文件失败,引用如下:

Fatal error: Uncaught exception 'DOMException' with message 'Invalid Character Error' in E:\Domain.com\siteMap-generator1.php:54 Stack trace: #0 E:\Domain.com\siteMap-generator1.php(54): DOMDocument->createElement('urlset xmlns=\\"...') #1 {main} thrown in X:\Domain.com\siteMap-generator1.php on line 54

在测试中,我看到该节点需要一个非常具体的名称/字符串:

$root = $dom->createElement(‘urlset 123’);  FAILS
$root = $dom->createElement(‘urlset-123');  WORKS

但关闭节点也平衡,例如:

<url>
    <urlset-123>
        <loc>some value</loc>
    </urlset-123>
<url>

问题:如何正确添加所需的命名空间并且不将其作为关闭节点元素的一部分?

我尝试了以下方法来附加值,但也失败了:

$dom->nameSpace = ' http://www.sitemaps.org/schemas/sitemap/0.9';

$root = $dom->createElement('urlset + nameSpace');

【问题讨论】:

标签: php xml domdocument


【解决方案1】:

像这样使用DOMDocument::createElementNS()

$root = $dom->createElementNS("http://www.sitemaps.org/schemas/sitemap/0.9", "urlset");

【讨论】:

    猜你喜欢
    • 2019-03-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-29
    • 1970-01-01
    相关资源
    最近更新 更多