Jump to content

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>';


}

Edited by davefootball123
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;
}

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.