当我将xmlns添加到使用DOMDocument
编写的xml时,我一直收到以下错误致命错误:未捕获的异常'DOMException',其中包含错误'无效字符错误'...
$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");
另外,即使我有formatOutput = true,我仍然把所有内容写成一条长行:
<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>
我试图设置一些东西,因此可以为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">
感谢您提供任何帮助。
答案 0 :(得分:4)
您对createElement
的致电完全是假的。您不能以这种方式添加属性。试试这个:
<?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");
?>