PHP DOMDocument-如何添加命名空间声明? [英] PHP DOMDocument - how to add Namespace declaration?
问题描述
我正在基于以下代码创建动态sitemap.xml
I’m creating a dynamic sitemap.xml based on the following code
<?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
This works but Google is not happy there is not a Namespace declaration in the 'urlset' node. Google error: "Your Sitemap or Sitemap index file doesn't declare the expected namespace: http://www.sitemaps.org/schemas/sitemap/0.9"
如果我将代码更改为:
$root = $dom->createElement('urlset
xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"');
无法生成xml文件并引用以下内容:
it fails to generate the xml file and references the following:
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
在测试中,我看到该节点需要一个非常特定的名称/字符串:
In testing I see that the node requires a very specific name/string:
$root = $dom->createElement(‘urlset 123’); FAILS
$root = $dom->createElement(‘urlset-123'); WORKS
但是关闭节点也有余额,例如:
BUT the closing node also balances such as:
<url>
<urlset-123>
<loc>some value</loc>
</urlset-123>
<url>
问题:如何正确添加所需的Nam espace并将它作为关闭节点元素的一部分吗?
QUESTION: How to properly add the required Namespace and also not have it as part of the closing node element?
我尝试了以下操作来附加值,但也失败了:
I tried the following to append the value but that also failed:
$dom->nameSpace = ' http://www.sitemaps.org/schemas/sitemap/0.9';
$root = $dom->createElement('urlset + nameSpace');
推荐答案
使用 DOMDocument :: createElementNS()
像这样:
Use DOMDocument::createElementNS()
like this:
$root = $dom->createElementNS("http://www.sitemaps.org/schemas/sitemap/0.9", "urlset");
这篇关于PHP DOMDocument-如何添加命名空间声明?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!