【问题标题】:How parse xml sitemap with PHP?如何用 PHP 解析 xml 站点地图?
【发布时间】:2020-04-18 14:48:32
【问题描述】:

我想在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() 提供的参数无效

【问题讨论】:

    标签: php xml parsing xml-parsing simple-html-dom


    【解决方案1】:

    如果你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

    【讨论】:

    • 为什么不“$xml_sitemap-> url as $url”?
    • @Borja 你可以这样做。可能是这样写的,以防出现更多元素。这样只会返回 url 元素。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-09-12
    • 1970-01-01
    • 1970-01-01
    • 2011-02-14
    • 2012-02-12
    • 2019-06-10
    • 2023-01-09
    相关资源
    最近更新 更多