Convert A sitemap.xml File To A urllist.txt File Using PHP

12th August 2008 - 2 minutes read time

If you create a script that produces a sitemap.xml file there is no point in adapting this script so that it creates a urllist.txt file. The best solution is to use this sitemap.xml file to create the urllist.txt. The following script will do exactly this.

  1. $lines = file('sitemap.xml');
  2. $allMatches = array();
  3.  
  4. foreach ( $lines as $line_number => $line ) {
  5. $line = trim($line);
  6. preg_match_all('/(?<=\<loc\>)(.*?)(?=\<\/loc\>)/U', $line, $matches,PREG_SET_ORDER);
  7. if($matches){
  8. if ( $matches[0][0] != '' ) {
  9. $allMatches[] = $matches[0][0];
  10. };
  11. };
  12. };
  13.  
  14. $list = '';
  15. foreach ( $allMatches as $url ) {
  16. $list .= $url."\n";
  17. };
  18. $fh = fopen('urllist.txt', "w+");
  19. fwrite($fh, $list);
  20. fclose($fh);
  21.  
  22. // print out list to provide some feedback...
  23. echo $list;

The script works by first loading the sitemap.xml file into an array using the file() function. The script then goes through all of the items in the array and picks out everything between the tags and puts these into an array. It then adds these to a file called urllist.txt but also prints out the output to provide some indication that the script has run. This can be removed if you want to incorporate it into a larger script.

Add new comment

The content of this field is kept private and will not be shown publicly.