遍历 XML 文件以递归查找产品
Traverse XML file to find products recursively
我正在尝试读取远程 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>';
}
}
}
}
}
}
}
}
使用 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;
}
<?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>';
}
}
}
}
}
}
}
}
使用 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;
}