首页 > 解决方案 > 获取 XML 节点名称而不在 simplexml_load_file 中重复

问题描述

我正在使用以下代码获取 XML 的节点名称:

$url = 'https://www.toptanperpa.com/xml.php?c=shopphp&xmlc=e7ef2a0122';
$xml = simplexml_load_file($url) or die("URL Read Error");

echo $xml->getName() . "<br>";
    
    foreach ($xml->children() as $child) {
        echo $child->getName() . "<br>";
        
        foreach ($child->children() as $child2) {
            echo $child2->getName() . "<br>";
            
            foreach ($child2->children() as $child3) {
                echo $child3->getName() . "<br>";
                
                foreach ($child3->children() as $child4) {
                echo $child4->getName() . "<br>";
                }
            }
        }
    }

我正确地获取了节点和子节点,但是,它是重复的。

结果如下:

urunler
urun
urun_aktif
urun_metaKeywords
urun_metaDescription
urun_url
urun
urun_aktif
urun_metaKeywords
urun_metaDescription
urun_url

我应该使用array_unique还是有更好的方法?

谢谢

标签: phpxmlduplicatesnodes

解决方案


我使用了递归函数,这很简单

function getChildrens($x) {
  $children = array();
  array_push($children, $x->getName());
  foreach ($x->children() as $chld) {
    $children = array_merge($children, getChildrens($chld));
  }
  return array_unique($children);
}
echo implode("<br>", getChildrens($xml));

推荐阅读