luv2code
luv2code

Reputation: 1296

getting an xml node that matches another node

Hi I am trying to get 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 = simplexml_load_file('xml/codes.xml');

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

Upvotes: 1

Views: 83

Answers (2)

JeffChan
JeffChan

Reputation: 188

In most case, you may use xpath to do so. It is easier to read and handle complex search.

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

For more info about xpath syntax, just read http://www.w3schools.com/xpath/xpath_syntax.asp

Upvotes: 0

MrCode
MrCode

Reputation: 64536

$codes is the root node, not $codes->codes

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

Upvotes: 1

Related Questions