Jump to content

Formating else statement


Texan78

Recommended Posts

I am trying to configure an else if statement but I am little stumped on what the condition should be. I have a script that is supplied with data from a parsed XML. The data is then passed to a table to display dynamically. As in it only shows tables for the data if there is data to be displayed. So what I am trying to do is show a different table when there is no data that says basically "There are no reports at this time". I am just not sure what the condition should be to display the data table and if there is no data then show the alternate table. 

 

Here is the entire file. the $tdata is the one that shows the data. Then at the bottom you will see the print statement then I call this file with an include statement in another page to display.

<?php 
#######################################################################################
#
#  SPOTTER NETWORK STORM REPORTS
#  version 1.00
#
#  This program is free and no license is required.
#  
#
#  mesquiteweather.net
#
#######################################################################################

////  SETTINGS  ////


// Change colors
$bkgColor  = '#FFF';     // Background color   Examples:  "gray"  "#CCC"   "#CCCCCC"
$bc        = '#EEEEEE';  // Background color of table cells
$dtColor   = '#FFF';     // Date & time color  Examples:   "#FC0"   "#FFCC00"   "white"

////  END OF SETTINGS  ////

#######################################################################################

ini_set('display_errors','1');

// overrides from the Carter Lake Settings.php file (if applicable)
global $SITE;
if(isset($SITE['cacheFileDir'])) {$cacheFileDir = $SITE['cacheFileDir']; }
if (isset($SITE['imagesDir']))   {$imagesDir = $SITE['imagesDir'];} 
if(isset ($SITE['tz']))          {$ourTZ = $SITE['tz'];}
if(!function_exists('date_default_timezone_set')) {
  putenv("TZ=" . $ourTZ);
} else {
  date_default_timezone_set("$ourTZ");
}

// get path info & protect for cross-site scripting vulnerability
($_SERVER['REQUEST_URI']) ? $sri = htmlspecialchars(strip_tags($_SERVER['REQUEST_URI'])) : $sri = '';
$sri2 = str_replace('#SA', '', $sri);  // clean up for drop down menu

// set borders
$bbrdr = 'border-bottom:thin solid black';       // bottom
$lbrdr = 'border-left:thin solid black';         // left
$rbrdr = 'border-right:thin solid black';        // right
$tbrdr = 'border-top:thin solid black';          // top
$sbrdr = 'border-right:thin solid black; '.
         'border-left:thin solid black';         // side

$tData   = '';                                    // set variable
$nothing = 'There are currently no storm reports';                                    // set variable
$data = "http://www.spotternetwork.org/data.php";
$xml = simplexml_load_file($data);

foreach($xml->report as $report){

    $date = $report['stamp'];
    $narrative = $report['narrative'];
    $loc = $report['city1'];
    $tz = $report['tz'];
 
    $attrs = array();
            foreach($report->attributes() as $a => $b) {
    $attrs[$a] = $b;
}

$value = array_search('1', $attrs);

switch ($value) {
    case 'tornado':
        echo "Tornado";
        break;
    case 'funnelcloud':
        echo "Funnel Cloud";
        break;
    case 'wallcloud':
        echo "Wall Cloud";
        break;
    case 'rotation':
        echo "Rotation";
        break; 
    case 'hail':
        echo "Hail";
        break; 
    case 'wind':
        echo "Wind";
        break;
    case 'flood':
        echo "Flood";
        break;  
    case 'flashflood':
        echo "Flash Flood";
                             
}   
        
    $time = strtotime($date.' UTC');
    $dateInLocal = date("D g:i a", $time);
    
                 
// construct data for table display
  $tData .= '<table style="width: 100%; margin: 0px auto; background-color:<?php print ($bkgColor); ?>;" cellpadding="0" cellspacing="0">
 <tbody><tr>
  <td style="'.$tbrdr.';'.$sbrdr.'; padding: 2px 0px 2px 6px;  background-image:url('.$imagesDir.'headerbgd2.gif); color: '.$dtColor.'"><b>'.$string.'</b>
 </td>
 </tr>
 <tr>
  <td style="'.$sbrdr.'; padding: 6px 0px 0px 6px; background-color: '.$bc.';">Reported: <b>'.$dateInLocal.'</b>   -   </b>Location: <b>'.$loc.'</b></td>
 </tr>
 <tr>
  <td style="'.$sbrdr.'; line-height:5px; background-color:'.$bc.'"> </td>
 </tr>
 <tr>
  <td style="'.$sbrdr.'; '.$bbrdr.'; padding: 2px 6px 6px 6px; background-color:'.$bc.'">Description: <b>'.$narrative.'</b></td></tr></tbody></table>
<table style="margin-bottom: 5px;" border="0" cellpadding="0" cellspacing="0" width="100%"><tbody><tr><td><img alt="" src="images/1pixel.gif" border="0" height="7" width="7"></td><td class="shadow-mid" width="100%"><img alt="" src="images/1pixel.gif" border="0" height="7" width="7"></td><td><img alt="" src="images/1pixel.gif" border="0" height="7" width="7"></td></tr><tbody><table>';  
    
 }  

?>

<?php print $tData ?>

Then entire script works great, just need to tweak it do show a different table when there is no data and not sure how to define the condition based on the variables created from the XML that is embedded in the HTML $tdata table.

 

Any advice or suggestions would be greatly appreciated.

 

-Thanks

Link to comment
Share on other sites

No data meaning what? If there's no data will $xml->report be null, 0, an empty array? Check the documentation.

You'll have to figure out based on the XML document what qualifies as no data, and test for that.

Link to comment
Share on other sites

This is a very odd use of the ternary operator

 

// get path info & protect for cross-site scripting vulnerability
($_SERVER['REQUEST_URI']) ? $sri = htmlspecialchars(strip_tags($_SERVER['REQUEST_URI'])) : $sri = '';

 

Do this instead

 

$sri = ($_SERVER['REQUEST_URI']) ? htmlspecialchars(strip_tags($_SERVER['REQUEST_URI'])) : '';

 

I'm seeing a lot of other inefficiencies as well. For example

 

$attrs = array();
foreach($report->attributes() as $a => $b) {
$attrs[$a] = $b;
}

$value = array_search('1', $attrs);

switch ($value) {

 

You are looping through all of the values in attributes and putting into an array, then searching the array for a particular value and only using that value. It doesn't appear you are using the other values. Instead, just loop through attributes and "break;" the loop once you've found the value you want. Aslo, you can replace the switch with a simple array to convert the value to what you need

 

Also, you could use classes for the default style properties to make the code cleaner. In fact, you should consider setting any "static" output as a variable outside the loop instead of redefining it inside the loop - such as the table that goes after each record. Makes it easier to manage the code. There are other things as well.

 

Here is a rewrite of your code that should display the "no storm" message depending on the format of the XML file (as Jessica alluded to). This isn't tested since I don't have your file. So, there may be some minor typos and such. But, I tried to put it in a more logical format. I would definitely use classes instead of creating all that code in the script.

 

 

<?php
#######################################################################################
#
#  SPOTTER NETWORK STORM REPORTS
#  version 1.00
#
#  This program is free and no license is required.
#  
#
#  mesquiteweather.net
#
#######################################################################################

////  SETTINGS  ////


// Change colors
$bkgColor  = '#FFF';     // Background color   Examples:  "gray"  "#CCC"   "#CCCCCC"
$bc        = '#EEEEEE';  // Background color of table cells
$dtColor   = '#FFF';     // Date & time color  Examples:   "#FC0"   "#FFCC00"   "white"

////  END OF SETTINGS  ////

#######################################################################################

ini_set('display_errors','1');

## Start Configurable data ##

//Set message to display if there were not reports
$noStormMessage = 'There are currently no storm reports';

//Set path to data file
$data = "http://www.spotternetwork.org/data.php";

## End Configurable data ##

// overrides from the Carter Lake Settings.php file (if applicable)
global $SITE;
if(isset($SITE['cacheFileDir'])) {$cacheFileDir = $SITE['cacheFileDir']; }
if (isset($SITE['imagesDir']))   {$imagesDir = $SITE['imagesDir'];}
if(isset ($SITE['tz']))          {$ourTZ = $SITE['tz'];}
if(!function_exists('date_default_timezone_set'))
{
    putenv("TZ=" . $ourTZ);
}
else
{
    date_default_timezone_set("$ourTZ");
}

// get path info & protect for cross-site scripting vulnerability
$sri = ($_SERVER['REQUEST_URI']) ? str_replace('#SA', '', htmlspecialchars(strip_tags($_SERVER['REQUEST_URI']))) : '';


## ALL OF THESE STYLE PROPERTIES SHOULD BE PUT INTO CALSSES IN THE HTML
## ONLY VARIABLE STYLES SHOULD BE IN THE CODE HERE
// set borders
$bbrdr = 'border-bottom:thin solid black';       // bottom
$lbrdr = 'border-left:thin solid black';         // left
$rbrdr = 'border-right:thin solid black';        // right
$tbrdr = 'border-top:thin solid black';          // top
$sbrdr = 'border-right:thin solid black; '.
         'border-left:thin solid black';         // side
$tableStyle = "width: 100%; margin:0px auto; background-color:{$bkgColor};";
$td1Style = "{$tbrdr};{$sbrdr}; padding:2px 0px 2px 6px;  background-image:url({$imagesDir}headerbgd2.gif); color:{$dtColor};";
$td2Style = "{$sbrdr}; padding:6px 0px 0px 6px; background-color:{$bc};";
$td3Style = "{$sbrdr}; line-height:5px; background-color:{$bc}":
$td4Style = "{$sbrdr}; {$bbrdr}; padding: 2px 6px 6px 6px; background-color:{$bc}":

//Define table to display after each storm report
$afterTable = "<table style='margin-bottom: 5px;' border='0' cellpadding='0' cellspacing='0' width='100%'><tbody><tr><td><img alt='' src='images/1pixel.gif' border='0' height='7' width='7'></td><td class='shadow-mid' width='100%'><img alt='' src='images/1pixel.gif' border='0' height='7' width='7'></td><td><img alt='' src='images/1pixel.gif' border='0' height='7' width='7'></td></tr><tbody><table>\n";

$stormTypesAry = array(
    'tornado' => 'Tornado',
    'funnelcloud' => 'Funnel Cloud',
    'wallcloud' => 'Wall Cloud',
    'rotation' => 'Rotation',
    'hail' => 'Hail',
    'wind' => 'Wind',
    'flood' => 'Flood',
    'flashflood' => 'Flash Flood'
);


$xml = simplexml_load_file($data);

//Set initial output to false
$tData = false;
foreach($xml->report as $report)
{
    $date      = $report['stamp'];
    $time      = strtotime($date.' UTC');
    $dateInLocal = date("D g:i a", $time);
    $narrative = $report['narrative'];
    $loc       = $report['city1'];
    $tz        = $report['tz'];

    $stormType = 'Unknown';
    foreach($report->attributes() as $typeKey => $id)
    {
        if($id == 1)
        {
            if(array_key_exists($typeKey, $stormTypesAry))
            {
                $stormType = $stormTypesAry[$typeKey];
            }
            break;
        }
    }

    // construct data for table display
    $tData .= "<table style='{$tableStyle}' cellpadding='0' cellspacing='0'>\n";
    $tData .= "<tbody>\n";
    $tData .= "  <tr><td style='{$td1Style}'><b>{$stormType}</b></td></tr>\n";
    $tData .= "  <tr>\n";
    $tData .= "    <td style='{$td2Style}'>Reported: <b>{$dateInLocal}</b>   -   </b>Location: <b>{$loc}</b></td>\n";
    $tData .= "  </tr>\n";
    $tData .= "  <tr><td style='{$td3Style}'> </td></tr>\n";
    $tData .= "  <tr><td style='{$td4Style}'>Description: <b>{$narrative}</b></td></tr>\n";
    $tData .= "</tbody>\n";
    $tData .= "</table>\n";
    $tData .=  $afterTable;
    
 }  

//If no storms were in the source, set no storm message
if(!$tData)
{
    $tData = $noStormMessage;
}
 
echo $tData;
 
?>
Link to comment
Share on other sites

No data meaning what? If there's no data will $xml->report be null, 0, an empty array? Check the documentation.

You'll have to figure out based on the XML document what qualifies as no data, and test for that.

 

Thank you for the response. The XML feed is a feed of storm reports for a 3 hour span. If there is no reports currently then there is no data. I wasn't sure what the condition would be based off of to display the table if there was or wasn't data. I wasn't sure if it needed to based off the element report. That was the clarification I was looking for. 

 

-Thanks

Link to comment
Share on other sites

 

This is a very odd use of the ternary operator

// get path info & protect for cross-site scripting vulnerability
($_SERVER['REQUEST_URI']) ? $sri = htmlspecialchars(strip_tags($_SERVER['REQUEST_URI'])) : $sri = '';

 

I am creating this script for an open source template That was taken from the requirements of the template set. So it's not something I wrote or even paid much attention to.

 

 

I'm seeing a lot of other inefficiencies as well. For example

$attrs = array();
foreach($report->attributes() as $a => $b) {
$attrs[$a] = $b;
}

$value = array_search('1', $attrs);

switch ($value) {

That was based off an example I found. I am still novice at best so I am still learning. That was the code I was questioning.

 

 

You are looping through all of the values in attributes and putting into an array, then searching the array for a particular value and only using that value. It doesn't appear you are using the other values.

 

Well not all the attributes, just a few because those attributes are defined with a binary value to declare the selection. Instead of just one attribute that outputs the textual value. I.E. Instead of tornado="0" for no tornado or tornado="1" for tornado if that is the selection it should be just one attribute for something like weather="tornado" or weather="Hail" etc. That is not something I have control over that as that is how the person who has created the script to create the XML file I am getting the feed from has wrote it. I have an idea why it's done like that has those reports are generated from a form from users.

 

 

Instead, just loop through attributes and "break;" the loop once you've found the value you want. Aslo, you can replace the switch with a simple array to convert the value to what you need.

 

T

hat actually is much better way and what I was looking for.

 

 

Also, you could use classes for the default style properties to make the code cleaner. In fact, you should consider setting any "static" output as a variable outside the loop instead of redefining it inside the loop - such as the table that goes after each record. Makes it easier to manage the code. There are other things as well.

 

Right now this is just a concept so I was just trying to get something working. Then I would go back and clean everything up as it is a way to help me learn and know how the code is put together.

 

Here is a rewrite of your code that should display the "no storm" message depending on the format of the XML file (as Jessica alluded to). This isn't tested since I don't have your file. So, there may be some minor typos and such. But, I tried to put it in a more logical format. I would definitely use classes instead of creating all that code in the script.

 

Thanks for the rewrite. It works but it breaks my layout out and since I don't know how this is pieced together I am having to take a step back to debug something I am not familiar with how it works. That is why I won't it the way it was so I had a working concept then go back and clean it up. That way I know how it works and I learn at the same time new things.

 

This line is breaking my layout from the debugging I have been able to do. How to fix it I don't know.

$afterTable = "<table style='margin-bottom: 5px;' border='0' cellpadding='0' cellspacing='0' width='100%'><tbody><tr><td><img alt='' src='images/1pixel.gif' border='0' height='7' width='7'></td><td class='shadow-mid' width='100%'><img alt='' src='images/1pixel.gif' border='0' height='7' width='7'></td><td><img alt='' src='images/1pixel.gif' border='0' height='7' width='7'></td></tr><tbody><table>\n";

It is below the table output which is used as a table shadow when the table is constructed with this part.

// construct data for table display
    $tData .= "<table style='{$tableStyle}' cellpadding='0' cellspacing='0'>\n";
    $tData .= "<tbody>\n";
    $tData .= "  <tr><td style='{$td1Style}'><b>{$stormType}</b></td></tr>\n";
    $tData .= "  <tr>\n";
    $tData .= "    <td style='{$td2Style}'>Reported: <b>{$dateInLocal}</b>   -   </b>Location: <b>{$loc}</b></td>\n";
    $tData .= "  </tr>\n";
    $tData .= "  <tr><td style='{$td3Style}'> </td></tr>\n";
    $tData .= "  <tr><td style='{$td4Style}'>Description: <b>{$narrative}</b></td></tr>\n";
    $tData .= "</tbody>\n";
    $tData .= "</table>\n";
    $tData .=  $afterTable;

Please see the attached screen shots.

 

This is how it should look, pay attention to the footer.

 

Storm%20Spotter%20Network_Right.png

 

This is how it looks with it breaking.

 

Storm%20Spotter%20Network_Wrong.png

 

Since I am not familiar with how this is constructed I am not sure how to fix this. That is why I like getting a working concept first that way I know how it is built when I go back to clean it up and if something isn't working I know what I did that caused the problem so I know what to target it and helps me learn the logic.

 

Any suggestions why this is happening?

 

-Thanks

 

 

Link to comment
Share on other sites

Sorry, but creating clean, logical code from the beginning will reduce the total time to get your solution and reduce bugs. It take a little bit of extra time up front to do that, but you save much more time to actually complete since you are not going back and breaking things when you try to "clean up". So, I am not going to go back and rewrite the code into a less logical format.

 

I see no reason why that bit of code would break your format since it was a copy/paste of the code you were already using. I just put it in a format that was programatically easier to work with. But, I do see that you had an HTML error in what you previously provided. That table that follows ever storm alert has an table OPENING tag at the end.

 

 

. . . height='7' width='7'></td></tr><tbody><table>\n";

 

Try making that a closing table tag.

Link to comment
Share on other sites

Sorry, but creating clean, logical code from the beginning will reduce the total time to get your solution and reduce bugs. It take a little bit of extra time up front to do that, but you save much more time to actually complete since you are not going back and breaking things when you try to "clean up". So, I am not going to go back and rewrite the code into a less logical format.

 

I agree and it looks so much nicer and I am a perfectionist, I am just not experienced enough to do it from the start as I am still learning. Since I am self teaching myself and you are searching the net looking for answers and reading tutorials and documents I find so many different ways to do things. So it's easier for me right now to just get a working concept then work on building from that to improve it. I won't always do it this way but it makes it easier for me to learn as I see the wrong and right ways and how things should be properly written.

 

 

 

I see no reason why that bit of code would break your format since it was a copy/paste of the code you were already using. I just put it in a format that was programatically easier to work with. But, I do see that you had an HTML error in what you previously provided. That table that follows ever storm alert has an table OPENING tag at the end.

 

Wow, I can't believe I missed that. It's never been a problem before so that may be why I have never noticed it. That fixed it, I completely overlooked the obvious.

 

So if I could pick your brain one more time. I am cleaning up another code that is similar to this one but uses different data.

 

I have this code that creates a background color for the table cells based on the value of one of the elements from the XML.

$stormScale = '';

           switch($ef)
{
              case '0':
                    $stormScale = 'rgba(0, 255, 255, 0.2)';
                             break;
              case '1':
                    $stormScale = 'rgba(0, 0, 255, 0.1)';
                             break;
              case '2':
                    $stormScale = 'rgba(0, 255, 0, 0.2)';
                             break;
              case '3':
                    $stormScale = 'rgba(255, 255, 0, 0.1)';
                             break;
              case '4':
                    $stormScale = 'rgba(255, 153, 51, 0.2)';
                             break;
              case '5':
                    $stormScale = 'rgba(255, 0, 0, 0.2)';
                             break;
                             
}

How would I clean this up to a more efficient way? In my previous code it worked great but now it isn't working once I started cleaning up the script.

 

It is defined here....

$tableStyle = "width: 100%; margin:0px auto; background-color:{$bkgColor};";
$td1Style = "{$tbrdr};{$sbrdr}; padding:2px 0px 2px 6px;  background-image:url({$imagesDir}headerbgd2.gif); color:{$dtColor};";
$td2Style = "{$sbrdr}; padding:6px 0px 0px 6px; background-color:{$stormScale};";
$td3Style = "{$sbrdr}; line-height:5px; background-color:{$stormScale};";
$td4Style = "{$sbrdr}; {$bbrdr}; padding: 2px 6px 6px 6px; background-color:{$stormScale};";

Here is the complete full code.

<?php 
#######################################################################################
#
#  GOOGLE MAPS V3 KILLER TORNADOS
#  version 1.00
#
#  This program is free and no license is required.
#  
#
#  mesquiteweather.net
#
#######################################################################################

////  SETTINGS  ////

$GKey = 'ENTER_YOUR_KEY';                    // Enter your Google Maps API Key
$GImage = 'images/watermark_MW_GMap.png';     // Path to your watermark for your Google Map

// Change colors
$bc        = 'True';     // If True cell tables will show color of EF scale, set to false to use CSS style color
$dtColor   = '#FFF';     // Ttile Color  Examples:   "#FC0"   "#FFCC00"   "white"

////  END OF SETTINGS  ////

#######################################################################################

ini_set('display_errors','1');

// overrides from the Carter Lake Settings.php file (if applicable)
global $SITE;
if(isset($SITE['cacheFileDir'])) {$cacheFileDir = $SITE['cacheFileDir']; }
if (isset($SITE['imagesDir']))   {$imagesDir = $SITE['imagesDir'];}
if(isset ($SITE['tz']))          {$ourTZ = $SITE['tz'];}
if(!function_exists('date_default_timezone_set'))
{
    putenv("TZ=" . $ourTZ);
}
else
{
    date_default_timezone_set("$ourTZ");
}

// get path info & protect for cross-site scripting vulnerability
$sri = ($_SERVER['REQUEST_URI']) ? str_replace('#SA', '', htmlspecialchars(strip_tags($_SERVER['REQUEST_URI']))) : '';

//Set path to data file
$data = "http://www.spc.noaa.gov/climo/torn/xml/2013.xml";

$bbrdr = 'border-bottom:thin solid black';       // bottom
$lbrdr = 'border-left:thin solid black';         // left
$rbrdr = 'border-right:thin solid black';        // right
$tbrdr = 'border-top:thin solid black';          // top
$sbrdr = 'border-right:thin solid black; '.
         'border-left:thin solid black';         // side
$tableStyle = "width: 100%; margin:0px auto; background-color:{$bkgColor};";
$td1Style = "{$tbrdr};{$sbrdr}; padding:2px 0px 2px 6px;  background-image:url({$imagesDir}headerbgd2.gif); color:{$dtColor};";
$td2Style = "{$sbrdr}; padding:6px 0px 0px 6px; background-color:{$stormScale};";
$td3Style = "{$sbrdr}; line-height:5px; background-color:{$stormScale};";
$td4Style = "{$sbrdr}; {$bbrdr}; padding: 2px 6px 6px 6px; background-color:{$stormScale};";

//Define table to display after each storm report
$afterTable = "<table style='margin-bottom: 10px;' border='0' cellpadding='0' cellspacing='0' width='100%'><tbody><tr><td><img alt='' src='images/1pixel.gif' border='0' height='7' width='7'></td><td class='shadow-mid' width='100%'><img alt='' src='images/1pixel.gif' border='0' height='7' width='7'></td><td><img alt='' src='images/1pixel.gif' border='0' height='7' width='7'></td></tr><tbody></table>\n";


// Lets parse the XML feed
$xml = simplexml_load_file($data);

//Set initial output to false
    $tData = false;
foreach($xml->fatalities as $fatalities){

    $yrnum = $fatalities['yrnum'];
    $dt = $fatalities['dt'];
    $time = $fatalities['time'];
    $updateTime = DATE("g:i a", STRTOTIME($time));
    $tz = $fatalities['tz'];
    $ef = $fatalities['ef'];
    $location = $fatalities['location'];
    $state = $fatalities['st'];
    $watch = $fatalities['watch'];
    $watchn = str_replace("WT","WW","$watch");
    $deaths = $fatalities['deaths'];
  
  $stormScale = '';

           switch($ef)
{
              case '0':
                    $stormScale = 'rgba(0, 255, 255, 0.2)';
                             break;
              case '1':
                    $stormScale = 'rgba(0, 0, 255, 0.1)';
                             break;
              case '2':
                    $stormScale = 'rgba(0, 255, 0, 0.2)';
                             break;
              case '3':
                    $stormScale = 'rgba(255, 255, 0, 0.1)';
                             break;
              case '4':
                    $stormScale = 'rgba(255, 153, 51, 0.2)';
                             break;
              case '5':
                    $stormScale = 'rgba(255, 0, 0, 0.2)';
                             break;
                             
}

        
               
 // construct data for table display
    $tData .= "<table style='{$tableStyle}' cellpadding='0' cellspacing='0'>\n";
    $tData .= "<tbody>\n";
    $tData .= "  <tr><td style='{$td1Style}'><b>2013 Killer Tornado #{$yrnum}</b></td></tr>\n";
    $tData .= "  <tr>\n";
    $tData .= "    <td style='{$td2Style}'>Date: <b>{$dt}</b>   -   </b>Time: <b>{$updateTime}</b>   -   </b>EF: <b>{$ef}</b>   -   </             b>Fatalities: <b>{$deaths}</b>   -   Watch Issued: {$watchn}<b></a></td>\n";
    $tData .= "  </tr>\n";
    $tData .= "  <tr><td style='{$td3Style}'> </td></tr>\n";
    $tData .= "  <tr><td style='{$td4Style}'>County: <b>{$location}</b>   -   State: <b>{$state}</b></td></tr>\n";
    $tData .= "</tbody>\n";
    $tData .= "</table>\n";
    $tData .=  $afterTable;
    
 }  

?>

<?php print $tData ?>

What could I do to improve that?

 

-Thanks

 

 

 

 

Link to comment
Share on other sites

As I stated the very fist time, don't define the style properties in the code. You should create classes in the HTML <style> tags and then apply the classes to the elements in the PHP code. I only create the $td1Style, $td2Style, etc. because I did not see where you were starting your HTML code to do that and I wasn't going to invest a ton of time on this. I would have instead defined classes such as "td1style" (or something a little more descriptive) and then applied those class names to the elements.

 

Same goes for $stormScale. Don't define the properties in your code. Instead, define classes such as stormScale0, stormScale1, stormScale2, etc. Then you could set the class without needing any logic to do it

 

echo "<td class="stormScale{$ef}">{$omeVar}</td>\n";

 

See how that would make the class dynamic without any code needed to figure it ouot?

Edited by Psycho
Link to comment
Share on other sites

I think I must not be clear. Let me see if I can explain it a little better. I appreciate the help and suggestions. This is why I don't like having someone rewrite my entire code because I don't learn from it and if something doesn't work I have to wait and rely on forums instead of figuring it out myself. The original code wasn't final. It was just a concept.  It's a learning process that works for me.

 

This is what I am having problems with that is now not currently working.

$stormScale = '';

switch($ef)
{
case '0':
$stormScale = 'rgba(0, 255, 255, 0.2)';
break;
case '1':
$stormScale = 'rgba(0, 0, 255, 0.1)';
break;
case '2':
$stormScale = 'rgba(0, 255, 0, 0.2)';
break;
case '3':
$stormScale = 'rgba(255, 255, 0, 0.1)';
break;
case '4':
$stormScale = 'rgba(255, 153, 51, 0.2)';
break;
case '5':
$stormScale = 'rgba(255, 0, 0, 0.2)';
break;

What that is suppose to do is take the value of that variable and assign a color to it.

 

THEN the variable $stormScale is used as such to assign that color as a cell color based on the value and amended to the current class

$td4Style = "{$sbrdr}; {$bbrdr}; padding: 2px 6px 6px 6px; background-color:{$stormScale};";

Then that classis applied to the HTML in the PHP.

 

That's not my issue. I can sort out all the details for styling later and is not important to me right now as it appears to be correct.

 

 

The issue is this loop isn't working now and it was working fine before with my original code. I hope that is a little clearer.

 

-Thanks

Edited by Texan78
Link to comment
Share on other sites

I got it sorted, I was assigning variable before its creation. So I just moved the table styles after the switch and before the table was created and works perfectly now.

 

Only issue I am having is the fail over message if no data is not displaying. If there is no data it just displays a blank table with no data.

 

Mesquite%20Weather%20-%20No%20Data.png

 

Here is the current code.

<?php
#######################################################################################
#
#  GOOGLE MAPS V3 STATEWIDE ALERTS
#  version 1.00
#
#  This program is free and no license is required.
#  
#
#  mesquiteweather.net
#
#######################################################################################

////  SETTINGS  ////

$state     = 'Texas';     // Enter your state
$loc       = 'tx';        // Put the the two letter abbrevation of your state

// Change colors
$bkgColor  = '#FFF';     // Background color   Examples:  "gray"  "#CCC"   "#CCCCCC"
$bc        = '#EEEEEE';  // Background color of table cells
$dtColor   = '#FFF';     // Date & time color  Examples:   "#FC0"   "#FFCC00"   "white"

////  END OF SETTINGS  ////

#######################################################################################

ini_set('display_errors','1');

## Start Configurable data ##

//Set message to display if there were not report
$noStormMessage = 'There are currently no active watches, warnings or advisories';

//Set path to data file
$data = "http://alerts.weather.gov/cap/".$loc.".php?x=1";

## End Configurable data ##

// overrides from the Carter Lake Settings.php file (if applicable)
global $SITE;
if(isset($SITE['cacheFileDir'])) {$cacheFileDir = $SITE['cacheFileDir']; }
if (isset($SITE['imagesDir']))   {$imagesDir = $SITE['imagesDir'];}
if(isset ($SITE['tz']))          {$ourTZ = $SITE['tz'];}
if(!function_exists('date_default_timezone_set'))
{
    putenv("TZ=" . $ourTZ);
}
else
{
    date_default_timezone_set("$ourTZ");
}

// get path info & protect for cross-site scripting vulnerability
$sri = ($_SERVER['REQUEST_URI']) ? str_replace('#SA', '', htmlspecialchars(strip_tags($_SERVER['REQUEST_URI']))) : '';

// set borders
$bbrdr = 'border-bottom:thin solid black';       // bottom
$lbrdr = 'border-left:thin solid black';         // left
$rbrdr = 'border-right:thin solid black';        // right
$tbrdr = 'border-top:thin solid black';          // top
$sbrdr = 'border-right:thin solid black; '.
         'border-left:thin solid black';         // side

//Define table to display after each storm report
$afterTable = "<table style='margin-bottom: 5px;' border='0' cellpadding='0' cellspacing='0' width='100%'><tbody><tr><td><img alt='' src='images/1pixel.gif' border='0' height='7' width='7'></td><td class='shadow-mid' width='100%'><img alt='' src='images/1pixel.gif' border='0' height='7' width='7'></td><td><img alt='' src='images/1pixel.gif' border='0' height='7' width='7'></td></tr><tbody></table>\n";

//Set initial output to false
$tData = false;
$entries = simplexml_load_file($data);
if(count($entries)):
    //Registering NameSpace
    $entries->registerXPathNamespace('prefix', 'http://www.w3.org/2005/Atom');
    $result = $entries->xpath("//prefix:entry");

    foreach ($result as $entry):
        $event = $entry->children("cap", true)->event;
        $effective = $entry->children("cap", true)->effective;
        $expires = $entry->children("cap", true)->expires;
        $updateDate = date("D, M d, g:i a", strtotime($updated));	
        $effectiveDate = date("D, M d, g:i a", strtotime($effective));
        $expiresDate = date("D, M d, g:i a", strtotime($expires));
        $status = $entry->children("cap", true)->status;
        $severity = $entry->children("cap", true)->severity;
        $urgency = $entry->children("cap", true)->urgency;
        $area = $entry->children("cap", true)->areaDesc;
        
        $alertColor = '';

           switch($event)
{
              case 'Air Quality Alert':
                    $alertColor = 'rgba(128, 128, 128, 0.4)';
                              break;
              case 'Fire Weather Watch':
                    $alertColor = 'rgba(255, 222, 173, 0.4)';
                              break;
              case 'Red Flag Warning':
                    $alertColor = 'rgba(255, 20, 147, 0.4)';
                              break;
              case 'Special Weather Statement':
                    $alertColor = 'rgba(255, 228, 181, 0.4)';
                              break;
              case 'Severe Thunderstorm Warning':
                    $alertColor = 'rgba(255, 165, 0, 0.4)';
                              break;
              case 'Severe Thunderstorm Watch':
                    $alertColor = 'rgba(219, 112, 147, 0.4)';
                              break;               
              case 'Severe Weather Statement':
                    $alertColor = 'rgba(0, 255, 255, 0.4)';
                           
}

// Let's assign the table some styles
   $tableStyle = "width: 100%; margin:0px auto; background-color:{$bkgColor};";
   $td1Style = "{$tbrdr};{$sbrdr}; padding:2px 0px 2px 6px;  background-image:url({$imagesDir}headerbgd2.gif); color:{$dtColor};";
   $td2Style = "{$sbrdr}; padding:6px 0px 0px 6px; background-color:{$alertColor};";
   $td3Style = "{$sbrdr}; line-height:5px; background-color:{$alertColor};";
   $td4Style = "{$sbrdr}; {$bbrdr}; padding: 2px 6px 6px 6px; background-color:{$alertColor};";         

// construct data for table display
    $tData .= "<table style='{$tableStyle}' cellpadding='0' cellspacing='0'>\n";
    $tData .= "<tbody>\n";
    $tData .= "  <tr><td style='{$td1Style}'><b>{$event}</b></td></tr>\n";
    $tData .= "  <tr>\n";
    $tData .= "    <td style='{$td2Style}'>Effective: <b>{$effectiveDate}</b>   -   Expires: <b>{$expiresDate}</b>   -   Status: <b>{$status}</b>   -   Severity: <b>{$severity}</b>   -   Urgency: <b>{$urgency}</b></td>\n";
    $tData .= "  </tr>\n";
    $tData .= "  <tr><td style='{$td3Style}'> </td></tr>\n";
    $tData .= "  <tr><td style='{$td4Style}'>Issued For: <b>{$area}</b></td></tr>\n";
    $tData .= "</tbody>\n";
    $tData .= "</table>\n";
    $tData .=  $afterTable;  

       endforeach;
endif;
 
//If no storms were in the source, set no storm message
if(!$tData)
{
    $tData = $noStormMessage;
}
 
echo $tData;

?>

What am I missing and overlooking?

 

-Thanks

Link to comment
Share on other sites

Only issue I am having is the fail over message if no data is not displaying. If there is no data it just displays a blank table with no data.

 

So, let me get this strait. You expect me to try and read through your crappy code and tell you what is wrong. But, you can't be bothered with reading through code I provide. That is how you learn. Read the code and figure out what it is doing. if you don't understand something look at the manual and figure it out or ask questions.

 

I am providing free help on my own time. If you don't want the help that I provide, then I won't provide it. I wish you luck and hope you find a solution to your problem.

Link to comment
Share on other sites

So, let me get this strait. You expect me to try and read through your crappy code and tell you what is wrong.

 

I didn't ask you to read through the entire code and critic it.  I am not denying it is not crappy but I am still learning and it's what works for me so I know and have a understanding of the logic. Once I know how it functions then I can go back and clean it up so I know how it works. If I break it that's ok because I know where and why it broke. I ask about a specific problem and you took the liberty to rewrite the entire code and that is very generous but, I did not ask you to do that. I don't learn anything from someone else just doing it and demeaning me in the process. It's obvious you are well knowledgeable about php. There is no reason to demean someone for their lack of knowledge. That is why forums are around for people to ask questions and get help. Not to have people write them code for free for them.

 

But, you can't be bothered with reading through code I provide.

 

 

I did read through it but if I don't know the logic behind it then it doesn't help me because I have no idea behind the logic or where to begin to debug it. Least with my crappy code if something happens then I have an idea where to look and have an idea how to address or ask for help to the certain issue. I have actually applied a lot of that code it to other scripts to clean them up. So to assume I didn't read or go through it and learn from it is an inaccurate assumption.

 

Read the code and figure out what it is doing.

 

That would be easy if I knew what I was looking at and what it was suppose to do don't ya think?

 

 

I am providing free help on my own time. If you don't want the help that I provide, then I won't provide it.

 

I didn't ask for you to rewrite the entire code. I ask a specific question. If you like to offer suggestions on how to do something a better way then I am open but, to tell me I have to do it this way or this way is the best way or because this is how you do it and then get hostile and demeaning like you're getting when I choose not to do that way is completely unreasonable. I am comfortable doing what works for me at the moment which helps me learn and understand things at my pace, not someone else's pace. Please respect that.

 

If you didn't notice my last post I did study the code and figured out one my issues. Which came down to you moving the styles of my code that originally worked before which caused me more work for having to figure out why that was happening. Which is why I said it may be crappy code but it helps me have a understanding then I can go back and clean it up later. That's how I prefer to do it, because you don't that should not be a reason to demean me. That's your preference, not mine. But after all this I am back to square one to my original question and what I was trying to find out that still isn't working from the code you provided. So all you have done is cost me to do more work for things I wasn't even concerned with at the moment as it is just a concept and wasted time for one simple question that I still don't have resolved.

 

-Thanks!

Link to comment
Share on other sites

I've reread through all of my posts in this thread and I don't see any comments that were demeaning to you. I did state that I thought the code was "crappy", but I think even you admitted it is a mess. I tend to be blunt and just tell it like it is. It is not intended to hurt anyone's feelings.

 

Yes, I rewrote your code and that was not what you asked for. But, I did that for several reasons. 1) It makes it easier to work with the code and implement changes. When the logic in the code is haphazard it makes it difficult to even try and implement changes and have confidence that they won't cause regressions. 2) I know from years of experience on this forum, that if we do not help people to improve their coding process/style we will be helping the same people over and over again to fix the same problems or many problems that occur because the logic is confusing and leads to bugs. 3) If people learn how to do something in a "less optimal" way, that is what they will continue to do.If you learn to do something in a good process then you will continue that good process in the future.

 

You have a LOT of logic in your code around setting styles and such. All it does is make your code more confusing and error prone. It would really make your code cleaner and much easier to read/edit if you were to take all of that out and use a style sheet. All it takes is one errant character in your code to break the PHP code of the HTML output.

 

So again, I help on this forum on my own time and get nothing in return. If someone does not want the particular type of help I provide, that's fine, I'll just move on. But, I think it is presumptuous to tell me "how" I should provide help when you are getting it for free.

 

Again, good luck to finding a solution to your problem - no sarcasm intended.

Edited by Psycho
Link to comment
Share on other sites

Hi all

 

I have a client who wants to upload a picture, generate a feed using xml which then parses to there website. Because im new to all of this I wondered does anyone know any good tutorials which will help me achieve this using PHP???

 

I would be grateful of any one who can help me.

 

Thanks

 

Stuart

Link to comment
Share on other sites

Hi all

 

I have a client who wants to upload a picture, generate a feed using xml which then parses to there website. Because im new to all of this I wondered does anyone know any good tutorials which will help me achieve this using PHP???

 

I would be grateful of any one who can help me.

 

Thanks

 

Stuart

 

 

I would recommend starting a new thread for your issue.

Link to comment
Share on other sites

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.