In the above code the required data is URL and other data are optional . So we will use this data only to generate our xml file.
Like our previous example of storing data in mysql table , we will use z_db1.php ( read about z_db1.php file at connect to table ) to connect to MySQL database. We have used PDO query to get the records from table. Then we have used the file write functions to crate and write the content to our sitemap.xml file. Here is the complete code.
<!doctype html public "-//w3c//dtd html 3.2//en">
<html>
<head>
<title>Reading data from MySQL and generating sitemap XML file</title>
</head>
<body>
<?Php
include "z_db1.php";
//// Starting of xml file string ///
$body_content="<?xml version="1.0" encoding="UTF-8"?> n
<urlset xmlns="https://www.sitemaps.org/schemas/sitemap/0.9">n
"; // Store some text to enter inside the file
/////Reading from MySQL table //////
$sql="select url from file_dtl";
foreach ($dbo->query($sql) as $row) {
$body_content.="<url><loc>$row[url]</loc></url>n";
}
////// End of reading MySQL table //////
$body_content.="</urlset>"; // last part of the xml file
//// writing the content to xml file ////
$file_name="sitemap.xml"; // file name
$fp = fopen ($file_name, "w");
// Open the file in write mode, if file does not exist then it will be created.
fwrite ($fp,$body_content); // entering data to the file
fclose ($fp); // closing the file pointer
chmod($file_name,0777);
echo "Please check $file_name file ";
?>
</body>
</html>
Why to store data in MySQL table
As you can understand we can also create xml file by reading the files present inside the directory without storing them in a table. The main advantage of storing them in a table is we can set the priority , update schedule etc manually from an admin area for each file and then with that data generate a sitemap.xml file. Storing the file details in a table also helps us in planning further improvement to content by reading title, descriptions and keywords with H1 tags etc.
This way it can be part of a complete content management script.