How to extract urls from xml sitemap url using php?

Member

by addison , in category: PHP General , a month ago

How to extract urls from xml sitemap url using php?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by lindsey.homenick , a month ago

@addison 

To extract URLs from an XML sitemap URL using PHP, you can use the SimpleXML extension in PHP. Here is an example of how you can extract URLs from an XML sitemap URL:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
// URL of the XML sitemap
$url = 'https://www.example.com/sitemap.xml';

// Load the XML sitemap file
$xml = simplexml_load_file($url);

// Loop through each URL in the sitemap
foreach ($xml->url as $url) {
    echo $url->loc . "<br>";
}


In the above code, we first specify the URL of the XML sitemap file. We then use the simplexml_load_file function to load the XML sitemap file and store it in the $xml variable as a SimpleXMLElement object. We then loop through each <url> element in the sitemap and extract the <loc> element (which contains the URL) using the arrow notation ->.


You can further process or store these URLs as needed in your PHP code.