Home > Back-end >  Output from MysSQL query to xml file
Output from MysSQL query to xml file

Time:01-08

I have this code i am trying to create a sitemap from and i need some help. When i run the php file i get the output of the file on the screen but no sitemap.xml file is created, anyone know why ?

<?

$xmlfile = 'sitemap.xml';

// this variable will contain the XML sitemap that will be saved in $xmlfile
$xmlsitemap = '<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">';

// Connection data (server_address, name, password, database_name)
$hostdb = 'localhost';
$userdb = 'user';
$passdb = 'ps';
$namedb = 'db';

try {
  // Connect and create the PDO object
  $conn = new PDO("mysql:host=$hostdb; dbname=$namedb", $userdb, $passdb);
  $conn->exec("SET CHARACTER SET utf8");      // Sets encoding UTF-8

  // Define and perform the SQL SELECT query
  $sql = "SELECT id, shortUrl FROM shorturl WHERE id BETWEEN 15 AND 45000";
  $result = $conn->query($sql);

  // If the SQL query is succesfully performed ($result not false)
  if($result !== false) {
    // Parse the result set, and add the URL in the XML structure
    foreach($result as $row) {
      $xmlsitemap .= '
<br><br>
<url><br>
<loc>https://website.com/'. $row['shortUrl'] .'<loc><br>
<changefreq>monthly<changefreq>
<priority>1<priority><br>
<url>

';
    }
  }

CodePudding user response:

You have to write the content of your $xmlfile variable to a file.

Try file_put_contents('sitemap.xml', $xmlfile); after the foreach loop.

But i am wondering whether <br> works in xml

  •  Tags:  
  • Related