获取与另一个节点匹配的xml节点

时间:2012-04-30 16:08:46

标签: php xml simplexml

您好我想要 node that contains the text 116.. but what I am trying is not working. Any help would be greatly appreciated!!

XML (codes.xml):

<codes>
<condition>
<code>116</code>
<description>Moderate or heavy snow in area with thunder</description>
<day_icon>wsymbol_0012_heavy_snow_showers</day_icon>
<night_icon>wsymbol_0028_heavy_snow_showers_night</night_icon>
</condition>
<condition>
<code>392</code>
<description>Patchy light snow in area with thunder</description>
<day_icon>wsymbol_0016_thundery_showers</day_icon>
<night_icon>wsymbol_0032_thundery_showers_night</night_icon>
</condition>
</codes>

My PHP CODE TO CALL:

<codes>
<condition>
<code>116</code>
<description>Moderate or heavy snow in area with thunder</description>
<day_icon>wsymbol_0012_heavy_snow_showers</day_icon>
<night_icon>wsymbol_0028_heavy_snow_showers_night</night_icon>
</condition>
<condition>
<code>392</code>
<description>Patchy light snow in area with thunder</description>
<day_icon>wsymbol_0016_thundery_showers</day_icon>
<night_icon>wsymbol_0032_thundery_showers_night</night_icon>
</condition>
</codes>

2 个答案:

答案 0 :(得分:1)

$codes是根节点,而不是$codes->codes

foreach($codes->condition AS $match)
{
    if($match->code == "116")
    {
        echo $match->description;
    }
};

答案 1 :(得分:0)

在大多数情况下,您可以使用xpath来执行此操作。它更容易阅读和处理复杂的搜索。

$codes = simplexml_load_file('xml/codes.xml');
$nodes = $codes->xpath("/codes/condition[code=116]");
foreach ($nodes as $N)
  echo $N->description;

有关xpath语法的更多信息,请阅读http://www.w3schools.com/xpath/xpath_syntax.asp