遍历XML文件以递归查找产品

时间:2018-12-10 16:22:53

标签: php recursion xml-parsing simplexml

enter image description here我正在尝试读取远程XML文件以查找特定类别的产品。我面临问题,因为XML文件具有嵌套类别,并且每个类别都有产品。在准备递归函数时需要帮助,该函数将在给定类别名称的情况下输出特定类别的产品。 这是我开始的代码

<?php
    $xml = simplexml_load_file('https://www.deere.com/en/us-en.taxonomy');
    getProducts($xml);

    function getProducts($xml) {
        foreach ($xml as $obj) {
            if ($obj->getName() == 'en_us_tractors') { //if category name is en_us_tractors
                if ($obj->children()) {
                    foreach ($obj->children() as $child) {
                        echo '<h1>' . $child->name . '</h1>';
                        if ($child->products) {
                            foreach ($child->products as $product) {
                                foreach ($product as $p) {
                                    echo 'sku  is ' . $p->sku . '<br>';
                                    echo 'path  is ' . $p->path . '<br>';
                                }
                            }
                        }
                    }                       

                }


            }
        }
    }

1 个答案:

答案 0 :(得分:0)

使用XPath查找数据很简单,它可以找到所需类别内的所有产品...

$xml = simplexml_load_file('https://www.deere.com/en/us-en.taxonomy');
$products = $xml->xpath("//en_us_tractors//products/*");
foreach ( $products as $product ){
        echo $product->sku."/".$product->path.PHP_EOL;
}