[英]Problem in updating an XML file using PHP DOMDocument();
I am trying to write a function that updates the Site Map of a website or technically adds an entry to sitemap.xml file. 我试图编写一个功能来更新网站的站点地图,或者从技术上说,将一项添加到sitemap.xml文件中。 The standard structure of a Google sitemap can be seen here: http://www.sitemappro.com/google-sitemap.html 可以在此处查看Google网站地图的标准结构: http : //www.sitemappro.com/google-sitemap.html
Following is the code of that function: 以下是该函数的代码:
function AddEntry($loc,$lastmod,$changefreq,$priority){
$xmlDoc = new DOMDocument();
$xmlDoc->load("sitemap.xml");
$url []=array('loc' => $loc, 'lastmod' => $lastmod, 'changefreq'=> $changefreq, 'priority' =>$priority );
$r=$xmlDoc->createElement("url");
$xmlDoc->appendChild($r);
foreach($url as $key=>$value)
{
$r->appendChild($xmlDoc->createElement($key))->appendChild($xmlDoc->createTextNode($value));
}
$xmlDoc->save();
}
The above code is not working and giving this error: 上面的代码不起作用,并给出此错误:
"Fatal error: Uncaught exception 'DOMException' with message 'Invalid Character Error' in..." “致命错误:在消息中存在未捕获的异常'DOMException'和消息'无效字符错误'。”
Can you please help by correcting my code? 您能帮我更正我的代码吗? Thanks in advance. 提前致谢。
As pointed out in a comment the issue should be in this line 正如评论中指出的那样,问题应该在这一行中
$r->appendChild($xmlDoc->createElement($key))->appendChild($xmlDoc->createTextNode($value));
Most likely you're adding some url characters to your XML. 您很可能会在XML中添加一些url字符。 The problem is that you must escape them or surround your $value
with a CDATA section. 问题是您必须转义它们或将$value
包含在CDATA节中。 Otherwise the generated XML will be invalid and the xml library will throw that kind of exceptions. 否则,生成的XML将是无效的,并且xml库将引发此类异常。
PS I don't remember if the htmlentities function is good also for xml, I suppose that, but you'll need to investigate about that. PS我不记得htmlentities函数是否对xml也有用,我想是这样,但是您需要对此进行调查。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.