Search code examples
phpxmlparsingxml-parsingsimple-html-dom

How parse xml sitemap with PHP?


I want to print values inside elemnts of xml file but i have a problem.

This xml sitemap:

<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="/sitemap.xsl"?>
 <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
  <url><loc>https://www.example.com/1</loc></url>
  <url><loc>https://www.example.com/2</loc></url>
 </urlset>

and this is my code:

$url_sitemap = "file.xml";
$xml_sitemap = simplexml_load_file($url_sitemap);

foreach($xml_sitemap-> urlset -> url as $url){
 $link= $url->loc;
 print_r($link);
}

but i have this error: Warning: Invalid argument supplied for foreach() in


Solution

  • If you print_r($xml_sitemap); you'll see that it doesn't contain the urlset:

    SimpleXMLElement Object
    (
        [url] => Array
            (
                [0] => SimpleXMLElement Object
                    (
                        [loc] => https://www.example.com/1
                    )
    
                [1] => SimpleXMLElement Object
                    (
                        [loc] => https://www.example.com/2
                    )
    
            )
    
    )
    

    You can then use

    foreach ($xml_sitemap as $url) {
        echo $url->loc;
    }
    

    to output all locs