Question

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.

Was it helpful?

Solution

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");
?>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top