English / Deutsch | Druckversion

XML Sitemap Generator


Es gibt zwei Varianten des Sitemap Generators. Ein BASH Skript (Linux/Unix) und ein PHP Skript.

Sitemap Format: http://www.sitemaps.org/protocol.html

XML Sitemap Generator - BASH
XML Sitemap Generator - PHP


XML Sitemap Generator - BASH


Das BASH Skript nutzt WGET um die Webseite herunterzuladen. Als erster Parameter wird der URL der Webseite angegeben. Der zweite Parameter wird für die Ausgabedatei (Sitemap Datei) verwendet und ist optional. Siehe Zeilen 116-123 um Links zu ignorieren.

Beispiel 1 (Ausgabe in aktuellem Verzeichnis): sh sitemap.sh https://www.example.com

Beispiel 2: sh sitemap.sh https://www.example.com /var/www/mysite/sitemap.xml



sitemap.xml


Man muss die Sitemap Datei in der /robots.txt eintragen.

Beispiel Zeile für die robots.txt:

Sitemap: https://www.example.com/sitemap.xml


Download 1.0


Download sitemap.sh - Version 1.0 2020/01/16

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
#!/bin/bash

#======================================================
# Simple site crawler to create a search engine XML Sitemap.
# Version: 1.0
# License: GPL v2
# Free to use, without any warranty.
# Written by Elmar Hanlhofer https://www.plop.at
#======================================================
#
# sitemap.sh <URL> [sitemap file]
#
# Example: sh sitemap.sh https://www.example.com /var/www/mysite/sitemap.xml
#
#======================================================

# Init script.
OIFS="$IFS"
IFS=$'\n'

URL="$1"
SITEMAP="$2"

HEADER="Plop XML Sitemap Generator - BASH Script 1.0 2020/01/16 https://www.plop.at"
AGENT="Mozilla/5.0 (compatible; Plop BASH XML Sitemap Generator/1.0)"

echo $HEADER
echo

# Check URL parameter.
if [ "$URL" == "" ]
then

    echo "Error! No URL specified."
    echo "Example: \"sh $0 https://www.example.com\""
    exit 1

fi

# Check sitemap parameter. If none given, use "sitemap.xml".
if [ "$SITEMAP" == "" ]
then

    SITEMAP=sitemap.xml

fi


# Get the scheme, site and domain name.
tmp_http=$(echo $URL | cut -b1-7)
tmp_https=$(echo $URL | cut -b1-8)

if [ "$tmp_http" == "http://" ]
then

    SCHEME=$tmp_http
    SITE=$(echo $URL | cut -b8-)

elif [ "$tmp_https" == "https://" ]
then

    SCHEME=$tmp_https
    SITE=$(echo $URL | cut -b9-)

else

    echo "Error! No scheme. You have to use \"http://\" or \"https://\"."
    echo "  http://$URL"
    echo "or"
    echo "  https://$URL"
    exit 1

fi

DOMAIN=$(echo $SITE | cut -d/ -f1)


# Create temporary directory.
TMP=$(mktemp -d)


# Grab the website.
echo "Downloading \"$URL\" to temporary directory \"$TMP\"..."
WGET_LOG=sitemap-wget.log

wget \
     --recursive \
     --no-clobber \
     --page-requisites \
     --convert-links \
     --restrict-file-names=windows \
     --no-parent \
     --directory-prefix="$TMP" \
     --domains $DOMAIN \
     --user-agent="$AGENT" \
     $URL >& $WGET_LOG

if [ ! -d "$TMP/$SITE" ]
then
    echo
    echo "Error! See \"$WGET_LOG\"."
    echo
    echo "Removing \"$TMP\"."
    rm -rf "$TMP"
    
    exit 1
fi

# Get current directory and store it for later.
curr_dir=$(pwd)


# Go to the temporary directory.
cd "$TMP"

#==============================
# Change this for your needs.
# Example, exclude files from /print and /slide: 
#   files=$(find | grep -i html | grep -v "$SITE/print" | grep -v "$SITE/slide")

files=$(find | grep -i html)

#==============================

# Go back to the previous directory.
cd "$curr_dir"


# Generate the XML file
echo "<?xml version=\"1.0\" encoding=\"UTF-8\"?>
<!-- Created with $HEADER -->
<!-- Date: $(date +"%Y/%m/%d %H:%M:%S") -->
<urlset xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\"
        xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"
        xsi:schemaLocation=\"http://www.sitemaps.org/schemas/sitemap/0.9
        http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd\">" > "$SITEMAP"

echo "  <url>
    <loc>$URL</loc>
    <changefreq>weekly</changefreq>
    <priority>0.5</priority>
  </url>" >> "$SITEMAP"


for i in $files
do

echo "  <url>
    <loc>$SCHEME$(echo $i | cut -b3-)</loc>
    <changefreq>weekly</changefreq>
    <priority>0.5</priority>
  </url>" >> "$SITEMAP"

done

echo "</urlset>" >> "$SITEMAP"


# All done. Remove temporary files.
echo "$SITEMAP created."
echo "Removing \"$TMP\" and \"$WGET_LOG\"."
rm -rf "$TMP"
rm "$WGET_LOG"

echo "Done."



XML Sitemap Generator - PHP


Ich habe für mich ein kleines PHP Skript zum erstellen einer XML Sitemap Datei für Google und andere Suchmaschinen programmiert. Vielleicht können es auch andere brauchen.

Pläne für 2.5: Sitemap Index Datei für Websiten mit mehr als 50000 Seiten oder XML Dateien die größer als 10 MB sind. Gzip-Komprimierung für Sitemap Dateien.

Falls das PHP Skript langsam läuft, dann gibt es Probleme mit der DNS Namensauflösung. Ich habe derzeit keine Lösung für das Problem. Probieren Sie die BASH Version vom Sitemap Generator.


Das Skript


Um das Skript zu konfigurieren, ändern Sie die Einstellungen im Bereich von Zeile 62 bis 102. Zuerst setzen Sie die SITE Variable in der Zeile 68 mit der Adresse Ihrer Website.
Beispiel: define ("SITE", "https://www.example.com");

Das Skript kann als CLI Skript oder als Webseite verwendet werden. Ich empfehle die Verwendung als CLI Skript.

CLI Skripts werden von der Kommandozeile oder CRON (usw.) gestartet.

CLI Befehl zum Erstellen der XML Datei: php sitemap-2.4.php

Wenn das Programm durch den Webserver als Webseite gestartet wird, dann ändern Sie im Skript die Zeile 74 mit
   define ("CLI", true);
auf
   define ("CLI", false);


sitemap.xml


Man muss die Sitemap Datei in der /robots.txt eintragen.

Beispiel Zeile für die robots.txt:

Sitemap: https://www.example.com/sitemap.xml


Download 2.4


Download sitemap-2.4.php - Version 2.4 2018/02/04

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
<?php/************************************************************* Simple site crawler to create a search engine XML Sitemap. Version: 2.4 License: GPL v2 Free to use, without any warranty. Written by Elmar Hanlhofer https://www.plop.at ChangeLog: ---------- Version 2.4 2018/02/04 by Elmar Hanlhofer     * Print configuration settings     * Because of some confusion I moved the SITE configuration       check down to the program start      Version 2.3 2018/01/31 by Elmar Hanlhofer     * Save creation date in sitemap file     * Stop with error when user did not set the SITE variable     * Replaced plop.at with example.com      * Remove commented text from HTML to avoid scanning        commented URLs Version 2.2 2017/10/12 by Elmar Hanlhofer      * Cut off page anchor from URL Version 2.1 2016/10/07 by Elmar Hanlhofer      * strpos fix (swap arguments) for first anchor - by William     * First anchor check optimized - by Elmar Hanlhofer Version 2.0 2016/08/11 by Elmar Hanlhofer      * Most program parts rewritten     * Using quotes on define command     * Supporting single and double quotes in href     * Notices disabled Version 1.0 2015/10/14 by Elmar Hanlhofer      * CLI / Website mode added     * Multiple extension support added     * Support for quoted URLs with spaces added     * Skip mailto links     * Converting special chars in the URLs for the XML file     * Added user agent     * Minor code updates Version 0.2 2013/01/16       * curl support - by Emanuel Ulses     * write url, then scan url - by Elmar Hanlhofer Version 0.1 2012/02/01 by Elmar Hanlhofer     * Initital release*************************************************************/    // Set the output file name.    define ("OUTPUT_FILE", "sitemap.xml");        // Set the start URL. Example: define ("SITE", "https://www.example.com");    define ("SITE", "");    // Set true or false to define how the script is used.    // true:  As CLI script.    // false: As Website script.    define ("CLI", true);    // Define here the URLs to skip. All URLs that start with the defined URL     // will be skipped too.    // Example: "https://www.example.com/print" will also skip    //   https://www.example.com/print/bootmanager.html    $skip_url = array (                       SITE . "/print",                       SITE . "/slide",                      );        // General information for search engines how often they should crawl the page.    define ("FREQUENCY", "weekly");        // General information for search engines. You have to modify the code to set    // various priority values for different pages. Currently, the default behavior    // is that all pages have the same priority.    define ("PRIORITY", "0.5");    // When your web server does not send the Content-Type header, then set    // this to 'true'. But I don't suggest this.    define ("IGNORE_EMPTY_CONTENT_TYPE", false);/*************************************************************    End of user defined settings.*************************************************************/function GetPage ($url){    $ch = curl_init ($url);    curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);    curl_setopt ($ch, CURLOPT_USERAGENT, AGENT);    $data = curl_exec($ch);    curl_close($ch);    return $data;}function GetQuotedUrl ($str){    $quote = substr ($str, 0, 1);    if (($quote != "\"") && ($quote != "'")) // Only process a string     {                                        // starting with singe or        return $str;                         // double quotes    }                                                     $ret = "";    $len = strlen ($str);        for ($i = 1; $i < $len; $i++) // Start with 1 to skip first quote    {        $ch = substr ($str, $i, 1);                if ($ch == $quote) break; // End quote reached        $ret .= $ch;    }        return $ret;}function GetHREFValue ($anchor){    $split1  = explode ("href=", $anchor);    $split2 = explode (">", $split1[1]);    $href_string = $split2[0];    $first_ch = substr ($href_string, 0, 1);    if ($first_ch == "\"" || $first_ch == "'")    {        $url = GetQuotedUrl ($href_string);    }    else    {        $spaces_split = explode (" ", $href_string);        $url          = $spaces_split[0];    }    return $url;}function GetEffectiveURL ($url){    // Create a curl handle    $ch = curl_init ($url);    // Send HTTP request and follow redirections    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);    curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);    curl_setopt ($ch, CURLOPT_USERAGENT, AGENT);    curl_exec($ch);    // Get the last effective URL    $effective_url = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL);    // ie. "http://example.com/show_location.php?loc=M%C3%BCnchen"    // Decode the URL, uncoment it an use the variable if needed    // $effective_url_decoded = curl_unescape($ch, $effective_url);    // "http://example.com/show_location.php?loc=München"    // Close the handle    curl_close($ch);    return $effective_url;}function ValidateURL ($url_base, $url){    global $scanned;            $parsed_url = parse_url ($url);            $scheme = $parsed_url["scheme"];            // Skip URL if different scheme or not relative URL (skips also mailto)    if (($scheme != SITE_SCHEME) && ($scheme != "")) return false;            $host = $parsed_url["host"];                    // Skip URL if different host    if (($host != SITE_HOST) && ($host != "")) return false;        // Check for page anchor in url    if ($page_anchor_pos = strpos ($url, "#"))    {        // Cut off page anchor        $url = substr ($url, 0, $page_anchor_pos);    }            if ($host == "")    // Handle URLs without host value    {        if (substr ($url, 0, 1) == '/') // Handle absolute URL        {            $url = SITE_SCHEME . "://" . SITE_HOST . $url;        }        else // Handle relative URL        {            $path = parse_url ($url_base, PHP_URL_PATH);                        if (substr ($path, -1) == '/') // URL is a directory            {                // Construct full URL                $url = SITE_SCHEME . "://" . SITE_HOST . $path . $url;            }            else // URL is a file            {                $dirname = dirname ($path);                // Add slashes if needed                if ($dirname[0] != '/')                {                    $dirname = "/$dirname";                }                    if (substr ($dirname, -1) != '/')                {                    $dirname = "$dirname/";                }                // Construct full URL                $url = SITE_SCHEME . "://" . SITE_HOST . $dirname . $url;            }        }    }    // Get effective URL, follow redirected URL    $url = GetEffectiveURL ($url);     // Don't scan when already scanned        if (in_array ($url, $scanned)) return false;        return $url;}// Skip URLs from the $skip_url arrayfunction SkipURL ($url){    global $skip_url;    if (isset ($skip_url))    {        foreach ($skip_url as $v)        {                       if (substr ($url, 0, strlen ($v)) == $v) return true; // Skip this URL        }    }    return false;            }function Scan ($url){    global $scanned, $pf;    $scanned[] = $url;  // Add URL to scanned array    if (SkipURL ($url))    {        echo "Skip URL $url" . NL;        return false;    }        // Remove unneeded slashes    if (substr ($url, -2) == "//")     {        $url = substr ($url, 0, -2);    }    if (substr ($url, -1) == "/")     {        $url = substr ($url, 0, -1);    }    echo "Scan $url" . NL;    $headers = get_headers ($url, 1);    // Handle pages not found    if (strpos ($headers[0], "404") !== false)    {        echo "Not found: $url" . NL;        return false;    }    // Handle redirected pages    if (strpos ($headers[0], "301") !== false)    {           $url = $headers["Location"];     // Continue with new URL        echo "Redirected to: $url" . NL;    }    // Handle other codes than 200    else if (strpos ($headers[0], "200") == false)    {        $url = $headers["Location"];        echo "Skip HTTP code $headers[0]: $url" . NL;        return false;    }    // Get content type    if (is_array ($headers["Content-Type"]))    {        $content = explode (";", $headers["Content-Type"][0]);    }    else    {        $content = explode (";", $headers["Content-Type"]);    }        $content_type = trim (strtolower ($content[0]));        // Check content type for website    if ($content_type != "text/html")     {        if ($content_type == "" && IGNORE_EMPTY_CONTENT_TYPE)        {            echo "Info: Ignoring empty Content-Type." . NL;        }        else        {            if ($content_type == "")            {                echo "Info: Content-Type is not sent by the web server. Change " .                     "'IGNORE_EMPTY_CONTENT_TYPE' to 'true' in the sitemap script " .                     "to scan those pages too." . NL;            }            else            {                echo "Info: $url is not a website: $content[0]" . NL;            }            return false;        }    }    $html = GetPage ($url);    $html = trim ($html);    if ($html == "") return true;  // Return on empty page        $html = preg_replace("/(\<\!\-\-.*\-\-\>)/sU", "", $html); // Remove commented text    $html = str_replace ("\r", " ", $html);        // Remove newlines    $html = str_replace ("\n", " ", $html);        // Remove newlines    $html = str_replace ("\t", " ", $html);        // Remove tabs    $html = str_replace ("<A ", "<a ", $html);     // <A to lowercase    $first_anchor = strpos ($html, "<a ");    // Find first anchor    if ($first_anchor === false) return true; // Return when no anchor found    $html = substr ($html, $first_anchor);    // Start processing from first anchor    $a1   = explode ("<a ", $html);    foreach ($a1 as $next_url)    {        $next_url = trim ($next_url);                // Skip empty array entry        if ($next_url == "") continue;                 // Get the attribute value from href        $next_url = GetHREFValue ($next_url);                // Do all skip checks and construct full URL        $next_url = ValidateURL ($url, $next_url);                // Skip if url is not valid        if ($next_url == false) continue;        if (Scan ($next_url))        {            // Add URL to sitemap            fwrite ($pf, "  <url>\n" .                         "    <loc>" . htmlentities ($next_url) ."</loc>\n" .                         "    <changefreq>" . FREQUENCY . "</changefreq>\n" .                         "    <priority>" . PRIORITY . "</priority>\n" .                         "  </url>\n");         }    }    return true;}    // Program start    define ("VERSION", "2.4");    define ("NL", CLI ? "\n" : "<br>");    // Print configuration    echo "Plop PHP XML Sitemap Generator Configuration:" . NL;    echo "VERSION: " . VERSION . NL;    echo "OUTPUT_FILE: " . OUTPUT_FILE . NL;    echo "SITE: " . SITE . NL;    echo "CLI: " . (CLI ? "true" : "false"). NL;    echo "IGNORE_EMPTY_CONTENT_TYPE: " . (IGNORE_EMPTY_CONTENT_TYPE ? "true" : "false") . NL;    echo "DATE: " . date ("Y-m-d H:i:s") . NL;    echo NL;        // SITE configuration check        if (!SITE)    {        die ("ERROR: You did not set the SITE variable at line number " .              "68 with the URL of your website!\n");    }    define ("AGENT", "Mozilla/5.0 (compatible; Plop PHP XML Sitemap Generator/" . VERSION . ")");    define ("SITE_SCHEME", parse_url (SITE, PHP_URL_SCHEME));    define ("SITE_HOST"  , parse_url (SITE, PHP_URL_HOST));    error_reporting (E_ERROR | E_WARNING | E_PARSE);    $pf = fopen (OUTPUT_FILE, "w");    if (!$pf)    {        echo "ERROR: Cannot create " . OUTPUT_FILE . "!" . NL;        return;    }    fwrite ($pf, "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" .                 "<!-- Created with Plop PHP XML Sitemap Generator " . VERSION . " https://www.plop.at -->\n" .                 "<!-- Date: " . date ("Y-m-d H:i:s") . " -->\n" .                 "<urlset xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\"\n" .                 "        xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n" .                 "        xsi:schemaLocation=\"http://www.sitemaps.org/schemas/sitemap/0.9\n" .                 "        http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd\">\n" .                 "  <url>\n" .                 "    <loc>" . SITE . "/</loc>\n" .                 "    <changefreq>" . FREQUENCY . "</changefreq>\n" .                 "  </url>\n");    echo "Scanning..." . NL;    $scanned = array();    Scan (GetEffectiveURL (SITE));        fwrite ($pf, "</urlset>\n");    fclose ($pf);    echo "Done." . NL;    echo OUTPUT_FILE . " created." . NL;?>


Hinweis für Version 1.0


Wenn nur die erste Seite gescannt wird, dann geben Sie einen Slash an das Ende des URLs in Zeile 34.

Beispiel: $url = "http://www.example.com/";

Danke an David Cordovez für die Info. Das Problem ist mit 2.x behoben.


Alte Versionen


sitemap-2.3.php - Version 2.3 2018/01/31
sitemap-2.2.php - Version 2.2 2017/10/12
sitemap-2.1.php - Version 2.1 2016/10/07
sitemap-2.0.php - Version 2.0 2016/08/11
sitemap-1.0.php - Version 1.0 2015/10/14
sitemap-0.2.php - Version 0.2 2013/01/16
sitemap-0.1.php - Version 0.1 2012/02/01


© 2024 by Elmar Hanlhofer
Die Seite wurde zuletzt am 16/Jan/2020 geändert.