1

我尝试下面的搜索代码,但它只显示第一个子节点。我的代码中是否缺少某些内容?

----目录.xml----

<?xml version="1.0" encoding="UTF-8"?>
<Catalog>
    <Category>
        <Name>CAT1</Name>
        <Location>
            <Room>Alpha</Room>
        </Location>
        <Location>
            <Room>Bravo</Room>
        </Location>  
        <Location>
            <Room>Charlie</Room>
        </Location>  
    </Category>
    <Category>
        <Name>CAT2</Name>
        <Location>
            <Room>Delta</Room>
        </Location>  
        <Location>
            <Room>Eagle</Room>
        </Location>  
        <Location>
            <Room>Falcon</Room>
        </Location>  
    </Category>
</Catalog>

----arr0.php----

<?php
$catalog = simplexml_load_file("catalog.xml");
$category = $catalog->Category;

foreach($category->Name as $name)
{
    $menu = (string)$name;
    $i = 0;
    if ($menu == "CAT1" )
{
        echo $category->Location->Room[$i];
        $i++;       
}
else 
{
        echo "No result";
}
}
?>

- - - - -输出 - - - - -

Α


布拉沃和查理从展示中消失了。需要有人建议我在哪里遗漏了什么?

谢谢

4

2 回答 2

0

尝试将您的代码修改为:

echo $category->Location[$i]->Room;
于 2012-11-07T06:59:56.410 回答
0

我想这就是你想要的

<?php
$catalog = simplexml_load_file("catalog.xml");
$category = $catalog->Category;
$found = false;
foreach($category as $c)
{
    $menu = (string) ($c->Name);
    if ($menu == "CAT1" )
    {
        foreach ($c->Location as $loc)
        {
            echo $loc->Room;
        }
        $found = true; break;
    }
}
if (!$found)
{
    echo "No result";
}
?>

break;如果您可以拥有多个具有已搜索名称元素的类别,请删除该语句。

于 2012-11-07T07:12:21.830 回答