davefootball123 Posted February 13, 2013 Share Posted February 13, 2013 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 More sharing options...
requinix Posted February 13, 2013 Share Posted February 13, 2013 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 } Link to comment https://forums.phpfreaks.com/topic/274458-check-if-element-exists-in-xml/#findComment-1412332 Share on other sites More sharing options...
davefootball123 Posted February 13, 2013 Author Share Posted February 13, 2013 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; } Link to comment https://forums.phpfreaks.com/topic/274458-check-if-element-exists-in-xml/#findComment-1412337 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.