Reputation: 1095
im trying to generate a sitemap.xml , here is simplified version of my code
$dom = new \DOMDocument();
$dom->encoding = 'utf-8';
$dom->xmlVersion = '1.0';
$dom->formatOutput = true;
$xml_file_name = './sitemap.xml';
$urlset = $dom->createElement('urlset');
$attr_ = new \DOMAttr('xmlns:xsi', "http://www.w3.org/2001/XMLSchema-instance");
$urlset->setAttributeNode($attr_);
$url_node = $dom->createElement('url');
$url_node_loc = $dom->createElement('loc', 'http://localhost' );
$url_node->appendChild($url_node_loc);
$url_node_lastmod = $dom->createElement('lastmod', '2021-08-03T22:17:47+04:30' );
$url_node->appendChild($url_node_lastmod);
$urlset->appendChild($url_node);
$dom->appendChild($urlset);
$dom->save($xml_file_name);
dd('done');
here is the output in my sitemap.xml
This XML file does not appear to have any style information associated with it. The document tree is shown below.
<urlset>
<url>
<loc>http://localhost</loc>
<lastmod>2021-08-03T22:17:47+04:30</lastmod>
</url>
</urlset>
i need to add some attributes to my urlset
tag , here is how i've did it
$attr_ = new \DOMAttr('xmlns:xsi', "http://www.w3.org/2001/XMLSchema-instance");
$urlset->setAttributeNode($attr_);
but for some reason this doesn't show up in my sitemap file , urlset has no attributes
Upvotes: 0
Views: 231
Reputation: 19502
This will not be a valid sitemap. Sitemaps use an XML namespace (https://www.sitemaps.org/protocol.html)
To create nodes with namespaces you should use the namespace aware DOM methods with the *NS
suffix. This will add namespace definitions as needed.
xmlns:xsi
is a namespace definition. They can be considered attributes nodes in the reserved namespace {http://www.w3.org/2000/xmlns/}.
$xmlns = [
'sitemap' => 'http://www.sitemaps.org/schemas/sitemap/0.9',
'xmlns' => 'http://www.w3.org/2000/xmlns/',
'xsi' => 'http://www.w3.org/2001/XMLSchema-instance',
];
$document = new \DOMDocument('1.0', 'utf-8');
$document->formatOutput = true;
$urlset = $document->appendChild(
$document->createElementNS($xmlns['sitemap'], 'urlset')
);
// explict namespace definition
$urlset->setAttributeNS(
$xmlns['xmlns'], 'xmlns:xsi', $xmlns['xsi']
);
$url_node = $urlset->appendChild(
$document->createElementNS($xmlns['sitemap'], 'url')
);
$url_node
->appendChild($document->createElementNS($xmlns['sitemap'], 'loc'))
->textContent = 'http://localhost';
$url_node
->appendChild($document->createElementNS($xmlns['sitemap'], 'lastmod'))
->textContent = '2021-08-03T22:17:47+04:30';
echo $document->saveXML();
Output:
<?xml version="1.0" encoding="utf-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<url>
<loc>http://localhost</loc>
<lastmod>2021-08-03T22:17:47+04:30</lastmod>
</url>
</urlset>
Upvotes: 1
Reputation: 4775
Use setAttribute()
instead of setAttributeNode()
.
$urlset->setAttribute('xmlns:xsi', 'http://www.w3.org/2001/XMLSchema-instance');
Upvotes: 1