如何用 PHP 解析 xml 站点地图?

How parse xml sitemap with PHP?

我想在 xml 文件的元素中打印值,但我遇到了问题。

这个 xml 站点地图:

<?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>

这是我的代码:

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

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

但我有这个错误:警告:为

中的foreach()提供的参数无效

如果你 print_r($xml_sitemap); 你会发现它不包含 urlset:

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

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

        )

)

然后您可以使用

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

输出全部locs