Scott Waddell
Scott Waddell

Reputation: 5

Getting multiple results from XML (and then discarding certain results based on keyword matching)

Novice PHP programmer here (if I can even call myself that). I am currently working on a way to loop through an XML document to grab every instance of a child object that does not contain a specific keyword and then display the results. I am able to do the aforementioned but only with the first child object that is found.

Examples Follow ...

Example XML There may be more than one instance of the following and I am trying to get the <title> child element from every instance that does not contain the word "Flood" or the phrase "There are no active watches, warnings or advisories".

<entry>
  <id>http://alerts.weather.gov/cap/wwaatmget.php?x=OHC095&amp;y=0</id>
  <updated>2013-04-16T20:00:01+00:00</updated>
  <author>
  <name>[email protected]</name>
  </author>
  <title>There are no active watches, warnings or advisories</title>
  <link href='http://alerts.weather.gov/cap/wwaatmget.php?x=OHC095&amp;y=0'/>
</entry>

Variables

//Lucas Co. Weather
$xml_string = file_get_contents("../../cache/weather_alerts-lucas.xml");
$weather_alerts_lucas = simplexml_load_string($xml_string);
$lucas_alert = ($weather_alerts_lucas->entry->title);
$no_alert =('There are no active watches, warnings or advisories');

Displaying The Results The first if statement determines whether there should be a scroll bar or not and the second if statement determines if a specific county should display information (there are multiple counties but I am only showing one here for simplicity).

if ("$lucas_alert"=="$no_alert" || fnmatch("*Flood*", $lucas_alert))
    {
      //Do Nothing. 
      } else {  
        echo "<div id='emergency_bar'>";
        echo "<span class='scroll_font' ... ...'>"; 
          if ("$lucas_alert"=="$no_alert" || fnmatch("*Flood*", $lucas_alert))
              { 
                //Do Nothing.   
                  } else {
                    echo "Lucas Co. - " . $lucas_alert . " // ";
                  }
        echo "</span>";
        echo "</div>";
      }

If I do it the way it is posted above it will only grab the first result and even if it grabbed multiple instances of <title> it would not display anything if one of the instances had the word "Flood" in it.

Thanks in advance. I'm not looking for someone to write code for me, just some direction.

Upvotes: 0

Views: 49

Answers (1)

michi
michi

Reputation: 6625

$xml = simplexml_load_string($x); // XML in $x
$no = "There are no active watches, warnings or advisories";

foreach ($xml->xpath("//title") as $title) {

    if ($title <> $no && strpos($title,"Flood") === false) echo "$title<br />";

}

see it working: http://codepad.viper-7.com/JVOoke

Upvotes: 1

Related Questions