简体   繁体   中英

PHP and sitemap.xml

I am planning to build a script that will create a sitemap.xml for my site, say, every day (cron will execute the script). Should I just build the XML string and save it as a file? Or would there be some benefit to using one of PHP's classes/functions/etc. for XML?

If I should be using some sort of PHP class/function/etc., what should it be?

I would suggest you to do cron to put all of the url in an array and store it as a cache. Then you could use this Kohana module to generate the sitemap.xml on the fly.

    // this is assume you have already install the module.
    $sitemap = new Sitemap;

    //this is assume you put an array of all url in a cache named 'sitemap'
    foreach($cache->get('sitemap') as $loc)
    {
        // New basic sitemap.
        $url = new Sitemap_URL;

        // Set arguments.
        $url->set_loc($loc)
            ->set_last_mod(1276800492)
            ->set_change_frequency('daily')
            ->set_priority(1);

        // Add it to sitemap.
        $sitemap->add($url);
    }

    // Render the output.
    $response = $sitemap->render();

    // Cache the output for 24 hours.
    $cache->set('sitemap', $response, 86400);

    // Output the sitemap.
    echo $response;

For simple XML it is often easier to just output the string. But the more complex your document gets, the more benefit you will get from using an XML library (either those included with PHP or a third party script) as it will help you to output correct XML.

For a sitemap, you would probably be best just writing the string.

It's simple format. Almost no structure. Just output it as string.

Unless you need to read/consume your own XML sitemap files, just output to string like others said. The XML sitemaps format is fairly simple. If you intend to support the subtypes as well then... Well I would still do it string based.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM