PHP:在XML中搜索字符串

时间:2012-11-07 06:54:28

标签: php xml

我尝试下面的搜索代码,但它只显示第一个子节点。我的代码中缺少什么东西?

---- ----的catalog.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";
}
}
?>

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

α


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

由于

2 个答案:

答案 0 :(得分:0)

尝试将代码修改为:

echo $category->Location[$i]->Room;

答案 1 :(得分: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";
}
?>

如果您可以使用搜索到的Name元素包含多个Category,则删除break;语句。