2011-08-05 48 views
0

我正在尝试编写一个更新网站的网站地图的功能,或者从技术上将条目添加到sitemap.xml文件中。一个谷歌地图的标准结构,可以在这里看到:http://www.sitemappro.com/google-sitemap.html使用PHP DOMDocument()更新XML文件时出现问题;

以下是该函数的代码:

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(); 
} 

上面的代码不工作并给予此错误:

“致命错误:未收集异常'DOMException',并在'...'中显示“无效字符错误”消息“

您可以通过更正我的代码来获得帮助吗?提前致谢。

+0

这是哪一行发生?推测foreach循环内的appendChild? –

回答

0

正如在评论中指出的问题应该是在这条线

$r->appendChild($xmlDoc->createElement($key))->appendChild($xmlDoc->createTextNode($value)); 

最有可能你要添加一些网址字符的XML。问题是你必须escape它们或包围您的$valueCDATA部分。否则,生成的XML将是无效的,XML库会抛出这种异常。

P.S.我不记得htmlentities函数是否也适用于xml,我想,但你需要调查一下。

相关问题