简体   繁体   中英

PHP DOMDocument Writing Sitemap Problems - Uncaught exception 'DOMException'

I keep getting the following error when I add xmlns to my xml written with DOMDocument

Fatal error: Uncaught exception 'DOMException' with message 'Invalid Character Error' in...

$xml = new DOMDocument("1.0", "UTF-8");
$xml_urlset = $xml->createElement('urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"');
$xml_url = $xml->createElement("url","this text");
$xml_urlset->appendChild($xml_url);
$xml->appendChild($xml_urlset);
$xml->formatOutput = true;
$xml->preserveWhiteSpace = false;
$xml->save("test.xml");

Also, even though I have formatOutput = true I still get everything written out as one long line:

<urlset>xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd"<url>this text</url></urlset>

I was trying to set things so this could be outputed for the urlset

<urlset
      xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9
            http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd">

Thank you for any help you can give me.

Your call to createElement is completely bogus. You can't add attributes that way. Try this:

<?php
$xml = new DOMDocument("1.0", "UTF-8");
$xml_urlset = $xml->createElement('urlset');
$xml_urlset->setAttribute('xmlns', 'http://www.sitemaps.org/schemas/sitemap/0.9');
$xml_urlset->setAttribute('xmlns:xsi', 'http://www.w3.org/2001/XMLSchema-instance');
$xml_urlset->setAttribute('xsi:schemaLocation', 'http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd');
$xml_url = $xml->createElement("url","this text");
$xml_urlset->appendChild($xml_url);
$xml->appendChild($xml_urlset);
$xml->formatOutput = true;
$xml->preserveWhiteSpace = false;
$xml->save("test.xml");
?>

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