Jump to content

Texan78

Members
  • Posts

    272
  • Joined

  • Last visited

Everything posted by Texan78

  1. Nevermind, I got it sorted. It should be style instead of class like so. All is good now. $bannerStyle = '"color: #FFF; width:100%; border: #FFF 1px solid; font-size:11px; font-weight:normal; font-family: Arial,Helvetica,sans-serif; text-align: center; background-color:' .$alertColor. '; margin-bottom:5px; padding: .2em 0em .2em 0em"'; $radiowarning = ' <div style='.$bannerStyle.'> <strong>SEVERE WEATHER ALERT - </strong>Listen now to our LIVE NOAA Weather Radio Stream <a href="'.$feed.'" onclick="return popup(this, "noaa")" title="Live NOAA Radio For Dallas County">[Click here to listen]</a> </div>';
  2. Yes, that seems to work perfect. I completely over looked the foreach. The last thing I can't seem to figure out which looks right is the variable for the CSS styling isn't applying. Does anyone see anything wrong? $bannerStyle = 'color: #FFF; width:100%; border: #fff 1px solid; font-size:11px; font-weight:normal; font-family: Arial,Helvetica,sans-serif; text-align: center; background-color:' .$alertColor. '; margin-bottom:5px; padding: .2em 0em .2em 0em'; $radiowarning = ' <div class="'.$bannerStyle.'"> <strong>SEVERE WEATHER ALERT - </strong>Listen now to our LIVE NOAA Weather Radio Stream <a href="'.$feed.'" onclick="return popup(this, "noaa")" title="Live NOAA Radio For Dallas County">[Click here to listen]</a> </div>';
  3. Thanks for the suggestion. That doesn't work. The XML parsing part is fine, there is not problem with that. I just need to be able to search for a certain alert and if that alert is presence in the event variable from the XML then display a message. Now this partly works. $radiowarning = "<div class='{$bannerStyle}'><b>SEVERE WEATHER ALERT - {$event}</b> ... Listen now to our LIVE NOAA Weather Radio Stream <a href='{$feed}'>[Click here to listen]</a></div>"; //If alerts are in the source, set alert message $alerts = array($event); $searchvalue = "Flood Warning"; if (in_array($searchvalue, $alerts)) { echo $radiowarning; } Problem is with this line "$searchvalue = "Flood Warning"; " I can't enter more than one value I need for it to look for in the event variable otherwise it gives me this error. I need it to be like this... $searchvalue = "Flood Watch", "Flood Warning", "Flash Flood Watch", "Flash Flood Warning", "Severe Thunderstorm Watch", "Severe Thunderstorm Warning", "Tornado Watch", "Tornado Warning"; I have tried the whole needle and haystack method but the problem is as above. It will only look for one value. I can't have it look for multiple values. I just need a method to search for a certain alert which is created from the $event variable that is created from parsing the XML. If any of those alerts are present. I.E. in this case... "Flood Watch", "Flood Warning", "Flash Flood Watch", "Flash Flood Warning", "Severe Thunderstorm Watch", "Severe Thunderstorm Warning", "Tornado Watch", "Tornado Warning" Then display this message, echo $radiowarning; Which that variable is this. $radiowarning = "<div class='{$bannerStyle}'><b>SEVERE WEATHER ALERT - {$event}</b> ... Listen now to our LIVE NOAA Weather Radio Stream <a href='{$feed}'>[Click here to listen]</a></div>"; It should be something really easy in logic but for some reason I am really struggling with it. If X statement exists then echo X, is pretty much the gist of it where $events supplies the values to look for but, keep in mind, the values might now always be there because it is an XML file and changes constantly. Here is a test page. Works with one value but anymore it doesn't. http://www.mesquiteweather.net/wxtest.php
  4. Ok, let me see if I can explain this better as I am just not the best at explaining things but, I will do my best. This is just a small snipped but the primary core of the XML parsing. //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; include ('inc-alert-colors.php'); endforeach; endif; Now from the snippet I am only parsing this from the XML $event = $entry->children("cap", true)->event; That gives me the $event variable. Now the event variable could have 120+ possible values for event. But at the most only 1 event would be show maybe 2-3 depending on the situation. So I created an array for the list of the possible values I want to find and if it finds it then display a message which is this. //If alerts are in the source, set alert message $event = array( $event => "Flood Watch", $event => "Flood Warning", $event => "Flash Flood Watch", $event => "Flash Flood Warning", $event => "Severe Thunderstorm Watch", $event => "Severe Thunderstorm Warning", $event => "Tornado Watch", $event => "Tornado Warning" ); if (in_array("Flood Watch", "Flood Warning", "Flash Flood Watch", "Flash Flood Warning", "Severe Thunderstorm Watch", "Severe Thunderstorm Warning", "Tornado Watch", "Tornado Warning", $event)) { echo "Match Found!"; } So basically that means out of the possible 120+ values from $event only look for those and if those are found echo a message. That leads me to these errors which I have already explained in my first post so look back at it to get the details. So my objective is out of the 120+ possible events find those certain ones and if those certain ones are found then display a message. If not, do nothing. It is pretty simple and straight forward but not sure how to get around this small snag.
  5. Can an admin move this to "PHP Coding Help". I posted this in the wrong forum by mistake. It was late and I was tired and wasn't paying any attention.
  6. Thank you but I am not sure what you did. You added.... $searchvalue = "Flash Flood Watch"; //as example but I don't see what that does or the purpose of that. How do you get the value? I don't understand the logic.
  7. Hello, I have come across a small snag that I am not sure how to get around. I am getting this error. Now, I know why I am getting this error. I am parsing and XML file to create the variable to get the values for the array. Now this is where the problem comes in. Since there is 6 possible values I am trying to pull there is only 3 values being produced at the time by the variable from the XML file at the time. So where I am stuck is how can I set this array up to look for these values when they are present and otherwise ignore it when they aren't as they won't always be present so it doesn't throw an error? What I am trying to do is if the variable from the XML file produces said values in the array then show this. This meaning echo a message. Here is the array //If alerts are in the source, set alert message $event = array( $event => "Flash Flood Watch", $event => "Flash Flood Warning", $event => "Severe Thunderstorm Watch", $event => "Severe Thunderstorm Warning", $event => "Torndao Watch", $event => "Torndao Warning" ); if (in_array("Flash Flood Watch", "Flash Flood Warning", "Severe Thunderstorm Watch", "Severe Thunderstorm Warning", "Torndao Watch", "Torndao Warning", $event)) { echo "Match found"; } the variable $event is created from parsing the XML file which has the possible values but, if the XML doesn't contain those values at the time then I get that error. So how would I need to address this array so I don't get the error but the array still looks for those values if present and echo the statement? -Thanks
  8. That did the trick! I replace the <br /> in the preg_replace with the \n and presto! All is great in the universe again. Thank you and you too Ch0cu3r
  9. I never even thought of that but the logic behind it makes sense. So I have attached a screenshot and there doesn't appear to be any special characters preventing it which now really has me scratching my head but I think the code is right. I am puzzled. I thought maybe I wasn't using the ucwords right so I tried it with the stroupper and it worked. That's when I really was puzzled because the ucwords should work unless it is some how rendering the line break as characters maybe but if then shouldn't it read it as the next line? EDIT: Well scratch that idea. I removed the break and it still doesn't work even with that removed.
  10. I am completely puzzled. I am not sure what is causing this but this works. It will make all characters upper case but, I only need the first character of each word upper case $WXSIMtitles[$i] = strtoupper($WXSIMtitles[$i]); So when I try this, it doesn't work, only the first character is upper case. $WXSIMtitles[$i] = ucwords(strtolower($WXSIMtitles[$i])); This works.... $WXSIMtitles[$i] = strtoupper($WXSIMtitles[$i]); //$WXSIMtitles[$i] = ucwords(strtolower($WXSIMtitles[$i])); $WXSIMicons[$i] = "<strong>$WXSIMtitles[$i]</strong><br /><img src=\"$iconDir$WXSIMicon[$i]\" alt=\"".strip_tags($WXSIMcond[$i])."\" title=\"". strip_tags($WXSIMcond[$i]) ."\" /><br /> $WXSIMcond[$i]"; This does not... //$WXSIMtitles[$i] = strtoupper($WXSIMtitles[$i]); $WXSIMtitles[$i] = ucwords(strtolower($WXSIMtitles[$i])); $WXSIMicons[$i] = "<strong>$WXSIMtitles[$i]</strong><br /><img src=\"$iconDir$WXSIMicon[$i]\" alt=\"".strip_tags($WXSIMcond[$i])."\" title=\"". strip_tags($WXSIMcond[$i]) ."\" /><br /> $WXSIMcond[$i]"; What would be causing this?
  11. I have tried it in different orders and nether worked. I didn't write this script, I am just trying to make a small modification. I would agree nl2br would be a better option but not sure how to implement that with how it is currently written and don't really want to make a bunch of change if I don't need to just for one small modification. Here is how the variable is displayed. $WXSIMicons[$i] = "<strong>$WXSIMtitles[$i]</strong><br /> <img src=\"$iconDir$WXSIMicon[$i]\" alt=\"".strip_tags($WXSIMcond[$i])."\" title=\"". strip_tags($WXSIMcond[$i]) ."\" /><br /> $WXSIMcond[$i]"; Not quite sure how to format this correctly to use the ucfirst.
  12. Hello, I have some titles in which I am trying to capitalize the first letter of each word and I am running into a problem implementing it. I think it is because of the previous formatting with the pre_replace or I am just not doing something right. I am using the $str = ucwords($str) but it isn't working correctly. What am I doing wrong? $WXSIMtitles[$i] = ucwords($WXSIMtitles[$i]); $WXSIMtitles[$i] = preg_replace('! (\S+)$!',"<br />\\1",get_lang($WXSIMday[$i])); if (! preg_match('!<br />!',$WXSIMtitles[$i])) { '<strong>' . $WXSIMtitles[$i] .= '<br />'; // add line break to 'short' day titles } The first letter is capitalized but the first letter in the second word isn't. I.E. Afternoon & Night. -Thanks
  13. Are you serious? That is what it was? I knew it was easy and had to do with the placement of that logic and that is hard to post all I had tried but, I could have sworn I had tried it there as it makes the most sense. Oh well, it is now working correctly so apparently didn't try it there. Thank you so much for you help.
  14. Here is the complete file. I didn't post it all because it is lengthy and I am not sure actually what parts are actually needed. Most of it is settings at the top and the bottom is for the map. The print statement to display the table is at line 668 <?php // PHP script by Ken True, webmaster@saratoga-weather.org // quake-json.php // Version 1.00 - 08-Sep-2012 - initial release as quake-json.php // Version 1.01 - 09-Sep-2012 - fixed XHTML 1.0-Strict and removed ' GMT' from local time display // Version 1.02 - 12-Sep-2012 - added diagnostics, map control translations and optional target="_blank" for links // Version 1.03 - 04-Jan-2013 - added fix for USGS unix timestamp with trailing zero added // Version 1.04 - 23-May-2013 - added 'home' pin, settings for lat/long via calling page // Version 1.05 - 24-May-2013 - fixed a CSS styling error for white-space: spec $Version = 'quake-json.php V1.05 - 24-May-2013'; // error_reporting(E_ALL); // uncomment to turn on full error reporting // // script available at http://saratoga-weather.org/scripts.php // // you may copy/modify/use this script as you see fit, // no warranty is expressed or implied. // // Customized for: all earthquakes from the new GeoJSON feeds // http://earthquake.usgs.gov/earthquakes/feed/geojson/1.0/week // which displays all earthquakes > 1.0 magnitude in the past 7 days // // // output: creates XHTML 1.0-Strict HTML page (default) // Options on URL: // tablesonly=Y -- returns only the body code for inclusion // in other webpages. Omit to return full HTML. // magnitude=N.N -- screens results looking for Richter magnitudes of // N.N or greater. // distance=MMM -- display quakes with epicenters only within // MMM km of your location // example URL: // http://your.website/quake-json.php?tablesonly=Y&magnitude=2.1&distance=45 // would return data without HTML header/footer for earthquakes of // magnitude 2.1 or larger within a 45 mile radius of your location. // // Usage: // you can use this webpage standalone (customize the HTML portion below) // or you can include it in an existing page: /* <?php $doIncludeQuake = true; # uncomment ONE of the $setDistanceDisplay lines to use as template for distance displays # $setDistanceDisplay = 'mi (km)'; $setDistanceDisplay = 'mi'; # $setDistanceDisplay = 'km (mi)'; # $setDistanceDisplay = 'km'; $setDistanceRadius = 200; // same units as first unit in $setDistanceDisplay # NOTE: quakes of magnitude 1.0+ are available for USA locations only. # non-USA location earthquakes of magnitude 4.0+ are the only ones available from the USGS $setMinMagnitude = '2.0'; // minimum Richter Magnitude to display $setHighMagnitude = '4.0'; // highlight this Magnitude and greater $setMapZoomDefault = 7; // default zoom for Google Map 1=world to 13=street # script will use your $SITE[] values for latitude, longitude, timezone and time display format $setDoLinkTarget = true; // =true to have links open in new page, =false for XHTML 1.0-Strict include("quake-json.php"); ?> */ // no parms: include("quake-json.php"); // // // settings: -------------------------------------------------------------------- // change myLat, myLong to your station latitude/longitude, // set $ourTZ to your time zone // other settings are optional // // minRichter= smallest quake to display (world is 4.0+, USA is 1.0+ on USGS // cacheName is name of file used to store cached USGS webpage // // set to station latitude/longitude (decimal degrees) $myLat = 37.27153397; //North=positive, South=negative decimal degrees $myLong = -122.02274323; //East=positive, West=negative decimal degrees // The above settings are for saratoga-weather.org location $ourLocationName = 'Mesquite, TX'; // city/town name for lat/long above // $myLogo = "images/watermark_MW_GMap.png"; // Logo to place on top left of map $dtColor = '#FFF'; // Text color for your table title headings $width = '100%'; // Adjust the overall width for both info table and legend to fit your site. $ourTZ = "America/Los_Angeles"; //NOTE: this *MUST* be set correctly to // translate UTC times to your LOCAL time for the displays. // Use http://www.php.net/manual/en/timezones.php to find the timezone suitable for // your location. // // pick a format for the time to display ..uncomment one (or make your own) //$timeFormat = 'D, Y-m-d H:i:s T'; // Fri, 2006-03-31 14:03:22 TZone $timeFormat = 'D, d-M-Y H:i:s T'; // Fri, 31-Mar-2006 14:03:22 TZone // setting for how to display distances .. uncomment one below // note: will be overridden by $SITE['distanceDisplay'] or $setDistanceDisplay if it exists // $distanceDisplay = 'mi (km)'; // display for distances in 'N mi (K km)' // $distanceDisplay = 'mi'; // display for distances in 'N mi' // $distanceDisplay = 'km (mi)'; // display for distances in 'K km (N mi)' // $distanceDisplay = 'km'; // display for distances in 'K km' $minRichter = '2.0'; // minimum Richter scale earthquake to display $maxDistance = 200; // quake must be within this number of miles/kilometers to location // specified in $myLat, $myLong latitude/longitude // and miles/kilometers chosen by first entry in $distanceDisplay above $highRichter = "5.0"; //change color for quakes >= this magnitude $mapZoomDefault = 6; // default Google Map zoom entry for display (1=world, 13=street) $cacheFileDir = './'; // default cache file directory $cacheName = "quakesjson.txt"; // used to store the file so we don't have to // fetch it each time $refetchSeconds = 1800; // refetch every nnnn seconds $imagesDir = './ajax-images/'; $doLinkTarget = true; // =true to add target="_blank" to links in popups // end of settings ------------------------------------------------------------- if (isset($_REQUEST['sce']) && strtolower($_REQUEST['sce']) == 'view' ) { //--self downloader -- $filenameReal = __FILE__; $download_size = filesize($filenameReal); header('Pragma: public'); header('Cache-Control: private'); header('Cache-Control: no-cache, must-revalidate'); header("Content-type: text/plain"); header("Accept-Ranges: bytes"); header("Content-Length: $download_size"); header('Connection: close'); readfile($filenameReal); exit; } // Constants // don't change $baseURL or $fileName or script may break ;-) $mapMainURL = "http://earthquake.usgs.gov/earthquakes/map/"; //USGS website main link $fileName = "http://earthquake.usgs.gov/earthquakes/feed/geojson/1.0/week"; // end of constants // overrides from Settings.php if available if(file_exists("Settings.php")) {include_once("Settings.php");} //if(file_exists("common.php")) {include_once("common.php");} global $SITE,$missingTrans; if (isset($SITE['latitude'])) {$myLat = $SITE['latitude'];} if (isset($SITE['longitude'])) {$myLong = $SITE['longitude'];} if (isset($SITE['cityname'])) {$ourLocationName = $SITE['cityname'];} if (isset($SITE['tz'])) {$ourTZ = $SITE['tz']; } if (isset($SITE['timeFormat'])) {$timeFormat = $SITE['timeFormat'];} if (isset($SITE['cacheFileDir'])) {$cacheFileDir = $SITE['cacheFileDir']; } if (isset($SITE['distanceDisplay'])) {$distanceDisplay = $SITE['distanceDisplay']; } // end of overrides from Settings.php # Shim function if run outside of AJAX/PHP template set # these must be before the missing function is called in the source if(!function_exists('langtransstr')) { function langtransstr($item) { return($item); } } if(!function_exists('langtrans')) { function langtrans($item) { print $item; return; } } // overrides from including page if any if (isset($setDistanceDisplay)) { $distanceDisplay = $setDistanceDisplay; } if (isset($setDistanceRadius)) { $maxDistance = $setDistanceRadius; } if (isset($setMinMagnitude)) { $minRichter = $setMinMagnitude; } if (isset($setHighMagnitude)) { $highRichter = $setHighMagnitude; } if (isset($setMapZoomDefault)) { $mapZoomDefault = $setMapZoomDefault; } if (isset($setDoLinkTarget)) { $doLinkTarget = $setDoLinkTarget; } if (isset($setLatitude)) { $myLat = $setLatitude; } if (isset($setLongitude)) { $myLong = $setLongitude; } if (isset($setLocationName)) { $ourLocationName = $setLocationName; } if (isset($setTimeZone)) { $ourTZ = $setTimeZone; } if (isset($setTimeFormat)) { $timeFormat = $setTimeFormat; } // ------ start of code ------- // Check parameters and force defaults/ranges if ( ! isset($_REQUEST['tablesonly']) ) { $_REQUEST['tablesonly']=""; } if (isset($doIncludeQuake) and $doIncludeQuake ) { $tablesOnly = "Y"; } else { $tablesOnly = $_REQUEST['tablesonly']; // any nonblank is ok } if ($tablesOnly) {$tablesOnly = "Y";} if ( isset($_REQUEST['magnitude']) ) { $minRichter = preg_replace("/^[^\d\.]+$/",'',$_REQUEST['magnitude']); } if ($minRichter <= "1.0") {$minRichter = "1.0";} if ($minRichter >= "9.0") {$minRichter = "9.0";} if ( isset($_REQUEST['highmagnitude']) ) { $highRichter = preg_replace("/^[^\d\.]+$/",'',$_REQUEST['highmagnitude']); } if ($highRichter <= "1.0") {$highRichter = "1.0";} if ($highRichter >= "9.0") {$highRichter = "9.0";} if (isset($_REQUEST['distance']) ) { $maxDistance = preg_replace("/^[^\d]+$/",'',$_REQUEST['distance']); } if ($maxDistance <= "10") {$maxDistance = "10";} if ($maxDistance >= "15000") {$maxDistance = "15000";} // for testing only if ( isset($_REQUEST['lat']) ) { $myLat = $_REQUEST['lat']; } if ( isset($_REQUEST['lon']) ) { $myLong = $_REQUEST['lon']; } if ( isset($_REQUEST['testloc']) ) { setTestLoc($_REQUEST['testloc']); } // allows for test override if ( isset($_REQUEST['cache'])) {$refetchSeconds = 1; } $Lang = 'en'; // default language if ( isset($_REQUEST['lang'])) {$Lang = strtolower($_REQUEST['lang']); } $Lang = QJ_ISO_Lang($Lang); // use official abbreviation or 'en' as default // omit HTML <HEAD>...</HEAD><BODY> if only tables wanted // --------------- customize HTML if you like ----------------------- if (! $tablesOnly) { ?> <?php if($doLinkTarget) { // generate XHTML 1.0-Transitional ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <?php } else { // generate XHTML 1.0-Strict header ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <?php } // end DOCTYPE selector ?> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Refresh" content="300" /> <meta http-equiv="Pragma" content="no-cache" /> <meta http-equiv="Cache-Control" content="no-cache" /> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> <title><?php langtrans('Earthquakes of magnitude'); ?> <?php print $minRichter; ?> <?php langtrans('within'); ?> <?php print $maxDistance; ?> <?php langtrans('km'); ?></title> <style type="text/css"> body { margin: 0 auto; padding: 10px 20px 20px; width: 640px; font-family: Arial; font-size: 12pt; background-color: white; color: black; } #map-container { padding: 5px; border-width: 1px; border-style: solid; border-color: #ccc #ccc #999 #ccc; -webkit-box-shadow: rgba(64, 64, 64, 0.5) 0 2px 5px; -moz-box-shadow: rgba(64, 64, 64, 0.5) 0 2px 5px; box-shadow: rgba(64, 64, 64, 0.1) 0 2px 5px; width: 620px; display: none; } #map { width: 740px; height: 480px; } #actions { list-style: none; padding: 0; } #inline-actions { padding-top: 10px; } .item { margin-left: 20px; } </style> <script src="http://maps.google.com/maps/api/js?sensor=false&language=<?php print $Lang; ?>" type="text/javascript"></script> <script src="quake-json.js" type="text/javascript"></script> </head> <body style="background-color:#FFFFFF;font-family:Arial, Helvetica, sans-serif;font-size:12px"> <?php } # Set timezone in PHP5/PHP4 manner if (!function_exists('date_default_timezone_set')) { putenv("TZ=" . $ourTZ); } else { date_default_timezone_set("$ourTZ"); } print "<!-- $Version -->\n"; print "<!-- lat=$myLat long=$myLong dist=$maxDistance mag=$minRichter distanceDisplay ='$distanceDisplay' -->\n"; // refresh cached copy of page if needed // fetch/cache code by Tom at carterlake.org $cacheName = $cacheFileDir.$cacheName; global $Debug; $Debug = ''; if (file_exists($cacheName) and filemtime($cacheName) + $refetchSeconds > time()) { print "<!-- using Cached version of $cacheName -->\n"; $rawhtml = implode('', file($cacheName)); } else { if($refetchSeconds == 1) { print "<!-- force cache reload -->\n"; } print "<!-- loading $cacheName from $fileName -->\n"; $rawhtml = QJ_fetchUrlWithoutHanging($fileName); print $Debug; $i = strpos($rawhtml,"\r\n\r\n"); $headers = substr($rawhtml,0,$i-1); $content = substr($rawhtml,$i+2); $RC = ''; if (preg_match("|^HTTP\/\S+ (.*)\r\n|",$rawhtml,$matches)) { $RC = trim($matches[1]); } if(!preg_match('|200 |',$RC)) { print "<!-- fetch returns RC='".$RC."' for $fileName -->\n"; } else { $fp = fopen($cacheName, "w"); if ($fp) { $write = fputs($fp, $rawhtml); fclose($fp); } else { print "<!-- unable to write cache file $cacheName -->\n"; } } print "<!-- loading finished. -->\n"; } //get the earthquake data JSON entries if(strpos($rawhtml,"\r\n\r\n") !== false) { list($headers,$content) = explode("\r\n\r\n",$rawhtml); // extract the 'meat' from the response } else { $headers = ''; $content = ''; } $utctimestamp = ''; if(preg_match('|\nLast-Modified: (.*)\n|Ui',$headers,$match)) { $udate = trim($match[1]); $utimestamp = strtotime($udate); print "<!-- data last modified $udate -->\n"; } elseif (file_exists($cacheName)) { $utimestamp = filemtime($cacheName); print "<!-- cache data saved ".gmdate($timeFormat,$utimestamp)." UTC -->\n"; } else { $utimestamp = time(); // get unix time for date print "<!-- using now as last modified date ".gmdate($timeFormat,$utimestamp)." UTC -->\n"; } $updatedUTC = langtransstr('Update time') . " = " . gmdate($timeFormat,$utimestamp); $updated = langtransstr('Update time') . " = " . date($timeFormat,$utimestamp); print "<!-- $updatedUTC UTC-->\n"; print "<!-- $updated Local-->\n"; print "<!-- content length=".strlen($content)." -->\n"; $quakeJSON = array(); if(strlen($content) > 10) { $quakeJSON = json_decode($content,true); } else { print "<!-- no content to parse -->\n"; print "<!-- USGS feed for earthquakes was not available at this time. See error messages above -->\n"; } if(strlen($content > 10) and function_exists('json_last_error')) { // report status, php >= 5.3.0 only switch (json_last_error()) { case JSON_ERROR_NONE: $error = '- No errors'; break; case JSON_ERROR_DEPTH: $error = '- Maximum stack depth exceeded'; break; case JSON_ERROR_STATE_MISMATCH: $error = '- Underflow or the modes mismatch'; break; case JSON_ERROR_CTRL_CHAR: $error = '- Unexpected control character found'; break; case JSON_ERROR_SYNTAX: $error = '- Syntax error, malformed JSON'; break; case JSON_ERROR_UTF8: $error = '- Malformed UTF-8 characters, possibly incorrectly encoded'; break; default: $error = '- Unknown error'; break; } $Status .= "<!-- JSON decode $error -->\n"; } $JQUAKES = array(); if(isset($quakeJSON['features'])) {$JQUAKES = $quakeJSON['features']; } print "<!-- found ".count($JQUAKES)." earthquake records -->\n"; /* JSON returned format as associative array: Array ( [type] => FeatureCollection [features] => Array ( [0] => Array ( [type] => Feature [properties] => Array ( [mag] => 2.2 [place] => 4km NNW of Brawley, California [time] => 1346625108 (UTC timestamp) [tz] => -420 (minutes offset from UTC for local time) [url] => http://earthquake.usgs.gov/earthquakes/eventpage/ci15209889 [felt] => 1 [cdi] => 2 [mmi] => [alert] => [status] => AUTOMATIC [tsunami] => [sig] => 75 [net] => ci [code] => 15209889 [ids] => ,ci15209889, [sources] => ,ci, [types] => ,dyfi,general-link,geoserve,nearby-cities,origin,scitech-link, ) [geometry] => Array ( [type] => Point [coordinates] => Array ( [0] => -115.5453 (longitude) [1] => 33.013 (latitude) [2] => 12.6 (depth in km) ) ) [id] => ci15209889 ) [1] => Array ( [type] => Feature [properties] => Array ( [mag] => 4.8 [place] => 80km SSW of Adak, Alaska [time] => 1346621542 [tz] => -720 [url] => http://earthquake.usgs.gov/earthquakes/eventpage/usc000cdrv [felt] => [cdi] => [mmi] => [alert] => [status] => REVIEWED [tsunami] => [sig] => 354 [net] => us [code] => c000cdrv [ids] => ,usc000cdrv, [sources] => ,us, [types] => ,eq-location-map,general-link,geoserve,historical-moment-tensor-map,historical-seismicity-map,nearby-cities,origin,p-wave-travel-times,phase-data,scitech-link,tectonic-summary, ) [geometry] => Array ( [type] => Point [coordinates] => Array ( [0] => -176.947 [1] => 51.1786 [2] => 46.34 ) ) [id] => usc000cdrv ) */ // examine, process and format each line -- omit quakes not // meeting the $minRichter and $maxDistance criteria $quakesFound = 0; $doneHeader = false; $comma = ''; $dmaxDist = $distanceDisplay; // load template if(preg_match('|^km|',$dmaxDist)) { $maxDistanceMi = round($maxDistance/1.609344,0); $maxDistanceKm = $maxDistance; } else { $maxDistanceMi = $maxDistance; $maxDistanceKm = round($maxDistance*1.609344,0); } $dmaxDist = preg_replace('|mi|',"$maxDistanceMi mi",$dmaxDist); $dmaxDist = preg_replace('|km|',"$maxDistanceKm km",$dmaxDist); $JSONout = "var data = {\"markers\": [\n"; $tgt = ''; if($doLinkTarget) {$tgt = ' target="_blank"';} foreach ($JQUAKES as $key => $onequake) { $magnitude = $onequake['properties']['mag']; $magnitude = sprintf("%1.1F",$magnitude); // ensure one decimal point displayed if ($magnitude >= "$minRichter") { // lets process it // load local variables $mapURL = $onequake['properties']['url']; // format quake date/time as local time at epicenter $Qtimestamp = $onequake['properties']['time']; if(strlen($Qtimestamp) > 10) {$Qtimestamp = substr($Qtimestamp,0,10); } $QDateTime = gmdate($timeFormat,$Qtimestamp+$onequake['properties']['tz']*60); $QDateTime = preg_replace('| GMT$|i','',$QDateTime); // Remove GMT string from local time text // extract lat/long/depth list($longitude,$latitude,$depth) = $onequake['geometry']['coordinates']; $kmDepth = round($depth,1); $miDepth = round($kmDepth/1.609344,1); $depth = $distanceDisplay; $depth = preg_replace('|mi|',"$miDepth mi",$depth); $depth = preg_replace('|km|',"$kmDepth km",$depth); preg_match('!^(\d+)km (\S+) of (.*)$!',$onequake['properties']['place'],$matches); if(isset($matches[2])) { $kmLoc = $matches[1]; $locDir = langtransstr($matches[2]); $locText = $matches[3]; $miLoc = round($kmLoc/1.609344,0); $location = $distanceDisplay; // load template $location = preg_replace('|mi|',"$miLoc mi",$location); $location = preg_replace('|km|',"$kmLoc km",$location); $location .= " $locDir ".langtransstr('of')." ".$locText; } else { $location = $onequake['properties']['place']; } // provide highlighting for quakes >= $highRichter if ($magnitude >= $highRichter) { $magnitude = "<span style=\"color: red\">$magnitude</span>"; $location = "<span style=\"color: red;\">$location</span>"; } $distanceM = round(distance($myLat,$myLong,$latitude,$longitude,"M")); $distanceK = round(distance($myLat,$myLong,$latitude,$longitude,"K")); $distKsort = sprintf("%06d",$distanceK); // make an alpha sort key $dText = $distanceDisplay; // load template $dText = preg_replace('|mi|',"$distanceM mi",$dText); $dText = preg_replace('|km|',"$distanceK km",$dText); $compareDistance = preg_match('|^km|',$distanceDisplay)?$distanceK:$distanceM; if ($compareDistance <= $maxDistance) { // only print 'close' ones $quakesFound++; // keep a tally of quakes for summary if (! $doneHeader) { // print the header if needed $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: 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"; $magScale = ''; switch($magnitude) { case '0': $magScale = 'rgba(0, 255, 255, 0.2)'; break; case '1': $magScale = 'rgba(0, 0, 255, 0.2)'; break; case '2': $magScale = 'rgba(0, 255, 0, 0.2)'; break; case '3': $magScale = 'rgba(255, 255, 0, 0.2)'; break; case '4': $magScale = 'rgba(255, 153, 51, 0.2)'; break; case '5': $magScale = 'rgba(255, 0, 0, 0.2)'; break; } // Let's assign the table some styles $tableStyle = "width:{$width}; 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:{$magScale};"; $td3Style = "{$sbrdr}; line-height:5px; background-color:{$magScale};"; $td4Style = "{$sbrdr}; {$bbrdr}; padding: 2px 6px 6px 6px; background-color:{$magScale};"; // construct data for table display $tData .= "<table style='{$tableStyle}' cellpadding='0' cellspacing='0'>\n"; $tData .= "<tbody>\n"; $tData .= " <tr><td style='{$td1Style}'><b>Magnitude {$magnitude}</b></td></tr>\n"; $tData .= " <tr>\n"; $tData .= " <td style='{$td2Style}'>Local Time: <span style=\"display: none; front-weight: strong\">$Qtimestamp</span>$QDateTime - Distance to Epicenter: <span style=\"display:none\">$distKsort</span><b>$dText</b></td>\n"; $tData .= " </tr>\n"; $tData .= " <tr><td style='{$td3Style}'> </td></tr>\n"; $tData .= " <tr><td style='{$td4Style}'>Epicenter Near: <b>{$location}</b></td></tr>\n"; $tData .= "</tbody>\n"; $tData .= "</table>\n"; $tData .= $afterTable; // --------------- customize HTML if you like ----------------------- ?> <?php print "<p><strong> ".langtransstr('Earthquakes in the past 7 days of magnitude')." $minRichter ".langtransstr('or greater within')." $dmaxDist <br/>$updated</strong></p>"; ?> <div id="map-container"> <div class="NWSround" style="text-align: center; padding: 10px 10px 10px 10px;"> <div id="GMwrapper"> <div id="map"></div> </div> </div> </div> <table width="100%" border="0" cellpadding="0" cellspacing="0"><tbody><tr><td><img alt="" src="images/1pixel.gif" height="7" width="7" border="0" /></td><td class="shadow-mid" width="100%"><img alt="" src="images/1pixel.gif" height="7" width="7" border="0" /></td><td><img alt="" src="images/1pixel.gif" height="7" width="7" border="0" /></td></tr></tbody></table> <?php if(count($JQUAKES) > 0) { // only do the legend if there is a map to produce ?> <script type="text/javascript"> // <![CDATA[ document.getElementById("map-container").style.display="block"; // got JavaScript enabled.. display map // only write the map legend if JavaScript is enabled var legend = '<p style="text-align: center"><img src="<?php print $imagesDir; ?>mma_20_green.png" height="20" width="12" alt="Home" style="vertical-align:middle"/> <?php echo $ourLocationName;?> | '+"\n"+ '<img src="<?php print $imagesDir; ?>mma_20_yellow.png" height="20" width="12" alt="Quake" style="vertical-align:middle"/> M<?php print $minRichter;?> - < M<?php print $highRichter; ?> | '+"\n"+ '<img src="<?php print $imagesDir; ?>mma_20_red.png" height="20" width="12" alt="Quake" style="vertical-align:middle"/> M<?php print $highRichter; ?>+ | '+ '<img src="<?php print $imagesDir; ?>m1.png" height="25" width="25" alt="Quake Cluster" style="vertical-align:middle"/> <?php langtrans("Cluster - click to expand details"); ?>'+"</p>\n"; document.write(legend); // ]]> </script> <?php } // end of produce legend if a map is produced ?> <noscript><p> <b><?php langtrans('Enable JavaScript to view the Google Map.'); ?></b> </p> </noscript> <?php $doneHeader = 1; } // end doneHeader // --------------- customize HTML if you like ----------------------- $JSONout .= "$comma"; $Jloc = strip_tags($location); $Jmag = strip_tags($magnitude); $JSONout .= " {\"loc\":\"$Jloc\",\"lat\":\"$latitude\",\"long\":\"$longitude\",\"mag\":\"$Jmag\",\"url\":\"$mapURL\",\"time\":\"$QDateTime\",\"dist\":\"$dText\",\"depth\":\"$depth\"}"; $comma = ",\n"; } //* else {print "<!-- lat='$latitude' long='$longitude' reject distance $distanceK > $maxDistance for $location -->\n"; } */// end maxdistance } // end minRichter } // end foreach loop // finish up. Write trailer info if ($doneHeader) { // --------------- customize HTML if you like ----------------------- ?> <?php print "<p>$quakesFound ". langtransstr("earthquakes found. Click on location or map links for more details from the <a href=\"$mapMainURL\">USGS</a>")."</p>\n"; } else { // --------------- customize HTML if you like ----------------------- if(strlen($content) > 10) { print "<p class=\"warning\" style=\"margin-top: 2em; text-align:center;\"><img src=\"images/alert.gif\" alt=\"\" /> " .langtransstr("No earthquakes of magnitude")." $minRichter ".langtransstr("or greater within")." $dmaxDist ".langtransstr("reported in last 7 days").".</p>\n"; } else { print "<h3>".langtransstr('The USGS feed for earthquakes was not available at this time.')."</h3>\n"; } } print $tData; $JSONout .= "\n]}\n"; print "<script type=\"text/javascript\">\n// <![CDATA[\n"; print $JSONout; print '// Generated Google Map code var markers = []; var imagesDir = \''.$imagesDir.'\'; // our marker/cluster images locations var highMag = '.$highRichter.'; // highlight quakes >= this value var doLinkTarget = '.$doLinkTarget.'; // generate target="_blank" option MarkerClusterer.IMAGE_PATH = imagesDir+"m"; // set to use our images for clusters function initialize() { // Google map will load this function at page-load var center = new google.maps.LatLng('.$myLat.','.$myLong.'); var options = { // options for Google map \'zoom\': '.$mapZoomDefault.', \'panControl\': false, \'center\': center, \'scaleControl\': true, \'zoomControlOptions\': { style: google.maps.ZoomControlStyle.SMALL, position: google.maps.ControlPosition.RIGHT_TOP }, \'mapTypeId\': google.maps.MapTypeId.HYBRID }; var cOptions = { // options for markerCluster \'gridSize\': 22, \'minimumClusterSize\': 4, \'averageCenter\': true }; var map = new google.maps.Map(document.getElementById("map"), options); function MyLogoControl(controlDiv) { controlDiv.style.padding = \'5px\'; var logo = document.createElement(\'IMG\'); logo.src = \'images/watermark_MW_GMap.png\'; logo.style.cursor = \'pointer\'; controlDiv.appendChild(logo); google.maps.event.addDomListener(logo, \'click\', function() { window.location = \'http://www.mesquiteweather.net\'; }); } var logoControlDiv = document.createElement(\'DIV\'); var logoControl = new MyLogoControl(logoControlDiv); logoControlDiv.index = 0; // used for ordering map.controls[google.maps.ControlPosition.TOP_LEFT].push(logoControlDiv); // Make the info window close when clicking anywhere on the map. google.maps.event.addListener(map, \'click\', closeInfoWindow); // Create a single instance of the InfoWindow object which will be shared // by all Map objects to display information to the user. var ourInfoWindow = new google.maps.InfoWindow(); var markerImageRed = new google.maps.MarkerImage(imagesDir+"mma_20_red.png"); var markerImageBlue = new google.maps.MarkerImage(imagesDir+"mma_20_blue.png"); var markerImageGreen = new google.maps.MarkerImage(imagesDir+"mma_20_green.png"); var markerImageYellow = new google.maps.MarkerImage(imagesDir+"mma_20_yellow.png"); var markerImageShadow = new google.maps.MarkerImage(imagesDir+"mma_20_shadow.png", new google.maps.Size(22, 20), new google.maps.Point(0,0), new google.maps.Point(0,20) ); for (var i = 0; i < data.markers.length; i++) { var latLng = new google.maps.LatLng(data.markers[i].lat, data.markers[i].long); var loc = data.markers[i].loc; var mag = data.markers[i].mag; var url = data.markers[i].url; var qtime = data.markers[i].time; var dist = data.markers[i].dist; var depth = data.markers[i].depth; var useMarkerIcon = markerImageYellow; // default to WX marker if (mag >= highMag) { useMarkerIcon = markerImageRed; } var title = "M"+mag+" - "+qtime; var tgt = \'\'; if(doLinkTarget > 0) {tgt = \' target="_blank"\'; } var popupHtml = "<small><a href=\""+url+"\""+tgt+"><strong>M"+mag+"</strong></a> - "+ qtime+" - '.langtransstr("Depth").': "+depth+"<br/>"+ loc+" <br/>"+ "'.langtransstr("Distance to epicenter").': "+dist+ "<br clear=\"left\"/></small>"; createMarker(map,latLng,useMarkerIcon,markerImageShadow,title,popupHtml); } // end of loop to create markers if (data.markers.length > 0 ) { var marker = new google.maps.Marker({ map: map, position: center, clickable: true, draggable: false, icon: markerImageGreen, shadow: markerImageShadow, title: "'.$ourLocationName.'", }); } var markerCluster = new MarkerClusterer(map, markers, cOptions); function createMarker (map,latLng, useMarkerIcon, markerImageShadow, title, popupHtml) { var marker = new google.maps.Marker({ map: map, position: latLng, clickable: true, draggable: false, icon: useMarkerIcon, shadow: markerImageShadow, title: title }); marker.popupHtml = popupHtml; google.maps.event.addListener(marker, \'click\', function() { openInfoWindow(marker); }); markers.push(marker); } function clearClusters(e) { e.preventDefault(); e.stopPropagation(); markerClusterer.clearMarkers(); } /** * Called when clicking anywhere on the map and closes the info window. */ function closeInfoWindow () { ourInfoWindow.close(); }; /** * Opens the shared info window, anchors it to the specified marker, and * displays the marker\'s position as its content. */ function openInfoWindow (marker) { ourInfoWindow.setContent(marker.popupHtml); ourInfoWindow.open(map, marker); } } // end of initialize function // now load it all up and display the map google.maps.event.addDomListener(window, \'load\', initialize); // ]]> '; print "</script>\n"; // print footer of page if needed // --------------- customize HTML if you like ----------------------- if (! $tablesOnly ) { ?> </body> </html> <?php } // ----------------------------functions ----------------------------------- // get contents from one URL and return as string function QJ_fetchUrlWithoutHanging($url,$useFopen=false) { // thanks to Tom at Carterlake.org for this script fragment global $Debug, $needCookie,$timeStamp,$TOTALtime; $overall_start = time(); if (! $useFopen) { // Set maximum number of seconds (can have floating-point) to wait for feed before displaying page without feed $numberOfSeconds=5; // Suppress error reporting so Web site visitors are unaware if the feed fails error_reporting(0); // Extract resource path and domain from URL ready for fsockopen $FullUrl = $url; $urlParts = parse_url($url); $domain = $urlParts['host']; if(isset($urlParts['port'])) { $port = $urlParts['port']; } else { $port = 80; } $resourcePath = $urlParts['path']; $resourcePath = preg_replace('|nocache|','?'.$timeStamp,$resourcePath); if(isset($urlParts['query'])) {$resourcePath .= "?" . $urlParts['query']; } if(isset($urlParts['fragment'])) {$resourcePath .= "#" . $urlParts['fragment']; } $T_start = QJ_microtime_float(); $hostIP = gethostbyname($domain); $T_dns = QJ_microtime_float(); $ms_dns = sprintf("%01.3f",round($T_dns - $T_start,3)); $Debug .= "<!-- GET $resourcePath HTTP/1.1 \n Host: $domain Port: $port IP=$hostIP-->\n"; // print "GET $resourcePath HTTP/1.1 \n Host: $domain Port: $port IP=$hostIP\n"; // Establish a connection $socketConnection = fsockopen($hostIP, $port, $errno, $errstr, $numberOfSeconds); $T_connect = QJ_microtime_float(); $T_puts = 0; $T_gets = 0; $T_close = 0; if (!$socketConnection) { // You may wish to remove the following debugging line on a live Web site $Debug .= "<!-- Network error: $errstr ($errno) -->\n"; // print "Network error: $errstr ($errno)\n"; } // end if else { $xml = ''; $getString = "GET $resourcePath HTTP/1.1\r\nHost: $domain\r\nConnection: Close\r\n"; if (isset($needCookie[$domain])) { $getString .= $needCookie[$domain] . "\r\n"; $Debug .= "<!-- cookie used '" . $needCookie[$domain] . "' for GET to $domain -->\n"; } $getString .= "Accept: text/plain,text/html\r\n"; $getString .= "\r\n"; // print "Sending:\n$getString\n\n"; fputs($socketConnection, $getString); $T_puts = QJ_microtime_float(); // Loop until end of file $TGETstats = array(); $TGETcount = 0; while (!feof($socketConnection)) { $T_getstart = QJ_microtime_float(); $xml .= fgets($socketConnection, 16384); $T_getend = QJ_microtime_float(); $TGETcount++; $TGETstats[$TGETcount] = sprintf("%01.3f",round($T_getend - $T_getstart,3)); } // end while $T_gets = QJ_microtime_float(); fclose ($socketConnection); $T_close = QJ_microtime_float(); } // end else $ms_connect = sprintf("%01.3f",round($T_connect - $T_dns,3)); if($T_close > 0) { $ms_puts = sprintf("%01.3f",round($T_puts - $T_connect,3)); $ms_gets = sprintf("%01.3f",round($T_gets - $T_puts,3)); $ms_close = sprintf("%01.3f",round($T_close - $T_gets,3)); $ms_total = sprintf("%01.3f",round($T_close - $T_start,3)); } else { $ms_puts = 'n/a'; $ms_gets = 'n/a'; $ms_close = 'n/a'; $ms_total = sprintf("%01.3f",round($T_connect - $T_start,3)); } $Debug .= "<!-- HTTP stats: dns=$ms_dns conn=$ms_connect put=$ms_puts get($TGETcount blocks)=$ms_gets close=$ms_close total=$ms_total secs -->\n"; // print "HTTP stats: dns=$ms_dns conn=$ms_connect put=$ms_puts get($TGETcount blocks)=$ms_gets close=$ms_close total=$ms_total secs \n"; // foreach ($TGETstats as $block => $mstimes) { // print "HTTP Block $block took $mstimes\n"; // } $TOTALtime+= ($T_close - $T_start); $overall_end = time(); $overall_elapsed = $overall_end - $overall_start; $Debug .= "<!-- fetch function elapsed= $overall_elapsed secs. -->\n"; // print "fetch function elapsed= $overall_elapsed secs.\n"; return($xml); } else { // print "<!-- using file function -->\n"; $T_start = QJ_microtime_float(); $xml = implode('',file($url)); $T_close = QJ_microtime_float(); $ms_total = sprintf("%01.3f",round($T_close - $T_start,3)); $Debug .= "<!-- file() stats: total=$ms_total secs -->\n"; // print " file() stats: total=$ms_total secs.\n"; $TOTALtime+= ($T_close - $T_start); $overall_end = time(); $overall_elapsed = $overall_end - $overall_start; $Debug .= "<!-- fetch function elapsed= $overall_elapsed secs. -->\n"; // print "fetch function elapsed= $overall_elapsed secs.\n"; return($xml); } } // end QJ_fetchUrlWithoutHanging // ------------------------------------------------------------------ function QJ_microtime_float() { list($usec, $sec) = explode(" ", microtime()); return ((float)$usec + (float)$sec); } // ------------ distance calculation function --------------------- //************************************** // // Name: Calculate Distance and Radius u // sing Latitude and Longitude in PHP // Description:This function calculates // the distance between two locations by us // ing latitude and longitude from ZIP code // , postal code or postcode. The result is // available in miles, kilometers or nautic // al miles based on great circle distance // calculation. // By: ZipCodeWorld // //This code is copyrighted and has // limited warranties.Please see http:// // www.Planet-Source-Code.com/vb/scripts/Sh // owCode.asp?txtCodeId=1848&lngWId=8 //for details. //************************************** // /*::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::*/ /*:: :*/ /*:: This routine calculates the distance between two points (given the :*/ /*:: latitude/longitude of those points). It is being used to calculate :*/ /*:: the distance between two ZIP Codes or Postal Codes using our:*/ /*:: ZIPCodeWorld(TM) and PostalCodeWorld(TM) products. :*/ /*:: :*/ /*:: Definitions::*/ /*::South latitudes are negative, east longitudes are positive:*/ /*:: :*/ /*:: Passed to function::*/ /*::lat1, lon1 = Latitude and Longitude of point 1 (in decimal degrees) :*/ /*::lat2, lon2 = Latitude and Longitude of point 2 (in decimal degrees) :*/ /*::unit = the unit you desire for results:*/ /*::where: 'M' is statute miles:*/ /*:: 'K' is kilometers (default):*/ /*:: 'N' is nautical miles :*/ /*:: United States ZIP Code/ Canadian Postal Code databases with latitude & :*/ /*:: longitude are available at http://www.zipcodeworld.com :*/ /*:: :*/ /*:: For enquiries, please contact sales@zipcodeworld.com:*/ /*:: :*/ /*:: Official Web site: http://www.zipcodeworld.com :*/ /*:: :*/ /*:: Hexa Software Development Center � All Rights Reserved 2004:*/ /*:: :*/ /*::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::*/ function distance($lat1, $lon1, $lat2, $lon2, $unit) { $theta = $lon1 - $lon2; $dist = sin(deg2rad($lat1)) * sin(deg2rad($lat2)) + cos(deg2rad($lat1)) * cos(deg2rad($lat2)) * cos(deg2rad($theta)); $dist = acos($dist); $dist = rad2deg($dist); $miles = $dist * 60 * 1.1515; $unit = strtoupper($unit); if ($unit == "K") { return ($miles * 1.609344); } else if ($unit == "N") { return ($miles * 0.8684); } else { return $miles; } } // ------------------------------------------------------------------ // testing function to safely set location/distance/zone using testloc= parm function setTestLoc ( $LOC ) { global $myLat,$myLong,$ourTZ,$maxDistance; if ($LOC == 'NZ') { $myLat = -37.07; $myLong = 174.35; $ourTZ = "Pacific/Auckland"; $maxDistance = 1000; // Yes, the above settings are for Brian Hamilton's Grahams Beach, NZ station // in honor of his outstanding work as author of Weather-Display software } elseif ($LOC == 'JP') { $myLat = 35.8499; $myLong = 139.97; $ourTZ = "Asia/Tokyo"; $maxDistance = 1000; } elseif ($LOC == 'MX') { $myLat = 19.3999; $myLong = -99.1999; $ourTZ = "America/Mexico_City"; $maxDistance = 1000; } elseif ($LOC == 'PR') { $myLat = 18.467248; $myLong = -66.108963; $ourTZ = "America/Puerto_Rico"; $maxDistance = 2000; } elseif ($LOC == 'AK') { $myLat = 61.21574783; $myLong = -149.86894226; $ourTZ = "America/Anchorage"; $maxDistance = 2000; } elseif ($LOC == 'IR') { $myLat = 35.68; $myLong = 51.3499; $ourTZ = "Asia/Tehran"; $maxDistance = 1000; } elseif ($LOC == 'GR') { $myLat = 37.983056; $myLong = 23.733056; $ourTZ = "Europe/Athens"; $maxDistance = 1000; } elseif ($LOC == 'SU') { $myLat = 3.0; $myLong = 100.0; $ourTZ = "Asia/Jakarta"; $maxDistance = 1000; } } // ------------------------------------------------------------------ function QJ_ISO_Lang ( $inLang) { global $SITE; if(isset($SITE['ISOLang'])) { $ISOlang = $SITE['ISOLang']; } else { $ISOlang = array ( // ISO 639-1 2-character language abbreviations from country domain 'af' => 'af', 'bg' => 'bg', 'ct' => 'ca', 'dk' => 'da', 'nl' => 'nl', 'en' => 'en', 'fi' => 'fi', 'fr' => 'fr', 'de' => 'de', 'el' => 'el', 'ga' => 'ga', 'it' => 'it', 'he' => 'he', 'hu' => 'hu', 'no' => 'no', 'pl' => 'pl', 'pt' => 'pt', 'ro' => 'ro', 'es' => 'es', 'se' => 'sv', 'si' => 'sl', ); } if(isset($ISOlang[$inLang])) { return($ISOlang[$inLang]); } else { return('en'); } } // --------------end of functions --------------------------------------- ?>
  15. Forgive me in advance. I will try to explain this the best I can and I may not explain it correctly so please bear with me and if anyone has any questions I will do my best to answer them. I have this script I am trying to modify to make some adjustments. Please note, I did not write this script. You can see the page from the link below. http://www.mesquiteweather.net/wxquake.php Below the map is a table. This is what I added from the variables that were available in the script. Here is my problem. It should be showing 3 separate events but it is only showing one. The table is displayed by using "print $tData;". I have moved it around but I can't get it to show all three events. It only shows 1 event or it shows 3 of the same event or it shows multiple duplicates of the same event. So it has something to do with the placement and the loop but, I can't figure out where to place it so it will display the correct events. This is the code I use to create the tables and display. $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: 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"; $magScale = ''; switch($magnitude) { case '0': $magScale = 'rgba(0, 255, 255, 0.2)'; break; case '1': $magScale = 'rgba(0, 0, 255, 0.2)'; break; case '2': $magScale = 'rgba(0, 255, 0, 0.2)'; break; case '3': $magScale = 'rgba(255, 255, 0, 0.2)'; break; case '4': $magScale = 'rgba(255, 153, 51, 0.2)'; break; case '5': $magScale = 'rgba(255, 0, 0, 0.2)'; break; } // Let's assign the table some styles $tableStyle = "width:{$width}; 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:{$magScale};"; $td3Style = "{$sbrdr}; line-height:5px; background-color:{$magScale};"; $td4Style = "{$sbrdr}; {$bbrdr}; padding: 2px 6px 6px 6px; background-color:{$magScale};"; // construct data for table display $tData .= "<table style='{$tableStyle}' cellpadding='0' cellspacing='0'>\n"; $tData .= "<tbody>\n"; $tData .= " <tr><td style='{$td1Style}'><b>Magnitude {$magnitude}</b></td></tr>\n"; $tData .= " <tr>\n"; $tData .= " <td style='{$td2Style}'>Local Time: <span style=\"display: none; front-weight: strong\">$Qtimestamp</span>$QDateTime - Distance to Epicenter: <span style=\"display:none\">$distKsort</span><b>$dText</b></td>\n"; $tData .= " </tr>\n"; $tData .= " <tr><td style='{$td3Style}'> </td></tr>\n"; $tData .= " <tr><td style='{$td4Style}'>Epicenter Near: <b>{$location}</b></td></tr>\n"; $tData .= "</tbody>\n"; $tData .= "</table>\n"; $tData .= $afterTable; Then like I said display that data using print $tData; Here is the snippet where I have inserted the code above. <?php $doneHeader = 1; } // end doneHeader // --------------- customize HTML if you like ----------------------- $JSONout .= "$comma"; $Jloc = strip_tags($location); $Jmag = strip_tags($magnitude); $JSONout .= " {\"loc\":\"$Jloc\",\"lat\":\"$latitude\",\"long\":\"$longitude\",\"mag\":\"$Jmag\",\"url\":\"$mapURL\",\"time\":\"$QDateTime\",\"dist\":\"$dText\",\"depth\":\"$depth\"}"; $comma = ",\n"; } //* else {print "<!-- lat='$latitude' long='$longitude' reject distance $distanceK > $maxDistance for $location -->\n"; } */// end maxdistance } // end minRichter } // end foreach loop // finish up. Write trailer info if ($doneHeader) { // --------------- customize HTML if you like ----------------------- print $tData; ?> <?php print "<p>$quakesFound ". langtransstr("earthquakes found. Click on location or map links for more details from the <a href=\"$mapMainURL\">USGS</a>")."</p>\n"; } else { // --------------- customize HTML if you like ----------------------- if(strlen($content) > 10) { print "<p class=\"warning\" style=\"margin-top: 2em; text-align:center;\"><img src=\"images/alert.gif\" alt=\"\" /> " .langtransstr("No earthquakes of magnitude")." $minRichter ".langtransstr("or greater within")." $dmaxDist ".langtransstr("reported in last 7 days").".</p>\n"; } else { print "<h3>".langtransstr('The USGS feed for earthquakes was not available at this time.')."</h3>\n"; } } This file is very code heavy so I am not sure what all I need to post. If I need to post more I can. Like I said, I didn't write this script I am just trying to add some modifications. I certainly wouldn't have wrote it this way. Any suggestions would be greatly welcomed as I am banging my head trying to figure this out and it should be rather simple task. -Thanks
  16. Ok well I found a way to get the percentage. This is what I did. Pretty simple and compact. Not sure if there is a better way or not. $val1 = $LRH_current; $val2 = $LRH_bankfull; $LRH_prec = ( $val1 / $val2) * 100; // 1 digit after the decimal point $LRH_prec = round($LRH_prec, 1);
  17. Ok, I got it sorted with the help of this code. Can anyone point me in the direction for a good tutorial for finding the % between the two numbers now? -Thanks
  18. That is pretty much the gist of it how it is. The data is created from parsing the XML file via SimpleXML. Here is a small example for one of them. SimpleXML feed parsing. //Parse Lake Ray Hubbard XML Data $site = simplexml_load_file($LRH_data);{ $LRH_bankfull = $site->sigstages[0]->bankfull; $LRH_current = $site->observed->datum[0]->primary; $LRH_vaild = $site->observed->datum[0]->valid; $LRH_updated = DATE("D, M d, g:i a", STRTOTIME($LRH_vaild)); } Then from there I take the data from those variables to get the departure. //Lets calculate the lake depatures from full pool $LRH_departure = $LRH_bankfull-$LRH_current; Then the new variable to get the departure is echo'd in the table. <td> <?php echo $LRH_departure;; ?> Ft</td> Pretty simple and straight forward but, yes it is rather strange it is rounding the number.
  19. Yes it is just the former. The Ft is added in the HTML after the echo. I am assuming with the "echo calcLevel" you replace the hard coded numbers with the variables? That looks exactly what I am looking for but not sure how to output that into the table.
  20. Thanks, the output you see in the screenshot is exactly how results are outputted using the echo as such. <td> <?php echo $LRH_departure; ?> Ft</td>
  21. Hello guys. I am looking for a better solution for what I have. I have done some google searches but my results didn't return much as most was related to date. I have this small script I have thrown together that is using data that I parse using SimpleXML. If you look at the picture there is a normal level. That is a set level. The current level is of course the current level. I need to find the difference between the two. If the current is less than the normal level I am trying to get it to display the difference with - and if the current is more than the normal level show +. What I have at the moment works ok but it doesn't show if it is -/+ and it doesn't figure in the dec point. Is there a better way to do this than what I have and also a way to pull the percentage as well? I.E. Current Level is X% of the Normal Level or in this case X% Full. Here is the code I am currently using to get the difference which is rather straight forward. $LRH_departure = $LRH_bankfull-$LRH_current; Here is a screenshot of the overall output. Note, this is still in development so it is very rough looking at the moment.
  22. Ah trim, I completely forgot about that one. That is exactly what I was looking for and works a lot better. Thanks guys!
  23. At the beginning. The data I am parsing adds ... at the beginning of the as well as other areas. The other areas are fine as I was able to remove the extra periods but, at the beginning of the paragraph there is a period that I would like to remove if posible but not certain how to go about that.
  24. I got it sorted like this. // Replaces all triple periods with single periods $summary = str_replace('...', '.', $summary); //now capitalize every letter after a . ? and ! followed by space $Summary = preg_replace_callback('/([.!?])\s*(\w)/', function ($matches) { return strtoupper($matches[1] . ' ' . $matches[2]); }, ucfirst(strtolower($summary))); But is there a way to remove periods from certain areas instead of all?
  25. Hello, I have a very simple problem I am sure for some. I have a file I am parsing using SimpleXML. The data includes extra periods after the sentences like this. This is causing me problems with doing preg_replace and strtoupper to capitalize the first letter of the sentence I think due to the extra periods after sentences since it is looking for only one period and not three. My question is how could I go about stripping two of the periods from the three? -Thanks
×
×
  • 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.