Tags
Asked 3 years ago
30 Jun 2021
Views 287
Jalon

Jalon posted

PHP script to automatically convert sitemap.xml to well formatted

PHP script to automatically convert sitemap.xml to well formatted
steave

steave
answered Apr 28 '23 00:00

Here is a sample PHP script that can help you convert sitemap.xml to a well-formatted format:



<?php

// Load sitemap.xml
$xml = simplexml_load_file("sitemap.xml");

// Create a new XML document
$newXml = new SimpleXMLElement('<?xml version="1.0" encoding="UTF-8"?><urlset></urlset>');

// Loop through each sitemap entry
foreach ($xml->url as $url) {

  // Create a new URL node
  $newUrl = $newXml->addChild('url');

  // Copy each sub-node
  foreach ($url->children() as $child) {
    $newUrl->addChild($child->getName(), (string) $child);
  }
}

// Save the new XML document to sitemap-formatted.xml
$newXml->asXML('sitemap-formatted.xml');

?>

This script loads the sitemap.xml file using the simplexml_load_file function and creates a new XML document using the SimpleXMLElement constructor. Then, it loops through each sitemap entry and copies each sub-node to the new XML document using addChild function.

Finally, the script saves the new XML document to sitemap-formatted.xml using the asXML function.

Note that this script assumes that sitemap.xml is in the same directory as the PHP file. You may need to modify the file path if your sitemap is stored in a different location.
Post Answer