DEV Community

Manish Chaudhary
Manish Chaudhary

Posted on

How I parsed sitemap.xml to save the links in database and make the sitemap dynamic in laravel

Below is the code snippet I used for this.

$xmlString = file_get_contents(public_path('sitemap.xml'));
    $xmlObject = simplexml_load_string($xmlString);
    $json = json_encode($xmlObject);
    $phpArray = json_decode($json, true);

    $usLinks = array_filter($phpArray['url'], function($linkData) {
        return strpos($linkData['loc'], '/us/') != false;
    });

    $usLinks = array_values(array_map(function($linkData) {
        return ['status' => 1, 'link' => $linkData['loc'], 'priority' => $linkData['priority']] ;
    }, $usLinks));

    array_unshift($usLinks, ['status' => 1, 'link' => 'https://sugarwish.com/', 'priority' => 1.00]);

    \App\DB\Sitemap::insert(
        $usLinks
    );
Enter fullscreen mode Exit fullscreen mode

Top comments (0)