Jump to content

Check if element exists in XML


davefootball123

Recommended Posts

Hi again everyone. I have successfully parsed most of a XML file however there is 1 thing that I am having trouble with. For one little section depending on the time of day...1 or 2 elements may exist and I have no clue how to check if element exists. Here is a sample of the xml below...sometimes it will be like the first...other times the second. My current code follows below the 2 XML examples. As you can see I have temperature[0] which will always work...however temperature[1] is the element that is sometimes there and sometimes not so I need to check if it exists first. Any help on how to do this would be great.

 

Dave,

 

<temperatures>
<textSummary>Low minus 6.</textSummary>
<temperature unitType="metric" units="C" class="low">-6</temperature>
</temperatures>

 

<temperatures>
<textSummary>Low minus 6.</textSummary>
<temperature unitType="metric" units="C" class="high">0</temperature>
<temperature unitType="metric" units="C" class="low">-6</temperature>
</temperatures>

 

foreach ($xml->forecastGroup->forecast->temperatures as $temps) {

echo $temps->temperature[0].'<br>';


}

Link to comment
https://forums.phpfreaks.com/topic/274458-check-if-element-exists-in-xml/
Share on other sites

Instead of a loop, use XPath to grab the elements you want directly: one is a "high" and one is a "low" temperature.

$high = current($xml->forecastGroup->forecast->xpath("temperatures[@class='high']"));
$low = current($xml->forecastGroup->forecast->xpath("temperatures[@class='low']"));

if ($high && $low) {
  // range is $low to $high
} else if ($high) {
  // high of $high
} else {
  // low of $low
}

Thanks very much. Just had to change to the code below and it worked wonderfully. Thank you very much.

$high = current($xml->forecastGroup->forecast->temperatures->xpath("temperature[@class='high']"));
$low = current($xml->forecastGroup->forecast->temperatures->xpath("temperature[@class='low']"));


if ($high && $low) {
 echo $high;
 echo $low;
} else if ($high) {
 echo $high;
} else {
 echo $low;
}

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.