简体   繁体   中英

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. The standard structure of a Google sitemap can be seen here: 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..."

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. The problem is that you must escape them or surround your $value with a CDATA section. Otherwise the generated XML will be invalid and the xml library will throw that kind of exceptions.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM