php google weather error handling issue - php

I have a php script that interacts with the google weather api.Everything works ok, but if I test it with a false location like "blahblah" I get a slew of errors in the browser despite having some validation in my script. The php code is as follows:
<?php
function googleWeather($location){
$url = "http://www.google.com/ig/api?weather=" . urlencode($location);
$xml = simplexml_load_file($url);
$current_conditions = $xml->xpath("/xml_api_reply/weather/current_conditions");
$temp_c = $current_conditions[0]->temp_c['data'];
$temp_f = $current_conditions[0]->temp_f['data'];
$result = sprintf("Current temperature is %s° Celsius %s° Fahrenheit",$temp_c,$temp_f);
return $result;
}
$loc = "blahblah";
$goog = googleWeather($loc);
if($goog == false){
echo "An error occurred";
}
else{
echo $goog;
}
?>
The error that is rendered in the browser is as follows:
( ! ) Notice: Undefined offset: 0 in C:\wamp2\www\phpAcademy\GoogleWeatherApi\TMP5c2a1z4emd.php on line 11
Call Stack
# Time Memory Function Location
1 0.1086 370080 {main}( ) ..\TMP5c2a1z4emd.php:0
2 0.1086 370184 googleWeather( ) ..\TMP5c2a1z4emd.php:23
( ! ) Notice: Trying to get property of non-object in C:\wamp2\www\phpAcademy\GoogleWeatherApi\TMP5c2a1z4emd.php on line 11
Call Stack
# Time Memory Function Location
1 0.1086 370080 {main}( ) ..\TMP5c2a1z4emd.php:0
2 0.1086 370184 googleWeather( ) ..\TMP5c2a1z4emd.php:23
( ! ) Notice: Undefined offset: 0 in C:\wamp2\www\phpAcademy\GoogleWeatherApi\TMP5c2a1z4emd.php on line 12
Call Stack
# Time Memory Function Location
1 0.1086 370080 {main}( ) ..\TMP5c2a1z4emd.php:0
2 0.1086 370184 googleWeather( ) ..\TMP5c2a1z4emd.php:23
( ! ) Notice: Trying to get property of non-object in C:\wamp2\www\phpAcademy\GoogleWeatherApi\TMP5c2a1z4emd.php on line 12
Call Stack
# Time Memory Function Location
1 0.1086 370080 {main}( ) ..\TMP5c2a1z4emd.php:0
2 0.1086 370184 googleWeather( ) ..\TMP5c2a1z4emd.php:23

Google returns the following for an invalid location
<xml_api_reply version="1"><weather module_id="0" tab_id="0" mobile_row="0" mobile_zipped="1" row="0" section="0"><problem_cause data=""/></weather></xml_api_reply>
This xml doesnt have the element "current_conditions" inside "weather". Thats casusing the error.
Check if exists then proceed which can be done with some thing like
if($current_conditions){
// you code here
} else {
return false;
}

I replaced blahblah with real city and it started to work.
Probably you enter your city address with wrong syntax.
Try to change your location, for example Zurich

The errors are pretty self-explanatory, $current_conditions doesn't contain what you think it does:
$current_conditions = $xml->xpath("/xml_api_reply/weather/current_conditions");
$temp_c = $current_conditions[0]->temp_c['data'];
// ^^^ undefined index
$temp_f = $current_conditions[0]->temp_f['data'];
// ^^^ Trying to access property of non object
You are not validating the result of $current_conditions:
if (is_array($current_conditions) && isset($current_conditions[0]))
{
$temp_c = $current_conditions[0]->temp_c['data'];
$temp_f = $current_conditions[0]->temp_f['data'];
}
Furthermore, you may need to validate the existence of the object properties, as well as the existence of the data key in those properties:
if (is_array($current_conditions) && isset($current_conditions[0]))
{
$cur = $current_conditions[0];
if (isset($cur->temp_c) && isset($cur->temp_c['data']))
{
$temp_c = $cur->temp_c['data'];
}
if (isset($cur->temp_f) && isset($cur->temp_f['data']))
{
$temp_f = $cur->temp_f['data'];
}
}
This is quite verbose, but to be absolutely sure to avoid these notices - it's what you have to do. You can and should turn off error reporting once you go live with your application. Notices are meant to help you debug code, if you understand how they're being generated and can safely ignore them, it may be OK.
And, if you feel confident that you know the API will return FALSE for an invalid query, just check if $current_conditions === FALSE and you can skip all the extra validation.

Related

get value from json file via php non array

I'm a beginner in json please help
I'm trying to access value of certain objects from an online published json file via php script and not able to do so following the examples from this forum
<?php
$str = file_get_contents('http://data.companieshouse.gov.uk/doc/company/02050399.json');
$json = json_decode($str, true);
$companyname = $json["primary topic"]["CompanyName"];
print $companyname;
?>
i get the following error
( ! ) Notice: Undefined index: primary topic in C:\wamp\www\json.php on line 4
Call Stack
# Time Memory Function Location
1 0.0000 244456 {main}( ) ..\json.php:0
I have tried single and double quotes, [0] for array but to no avail
You should have to use primaryTopic :
$str = file_get_contents('http://data.companieshouse.gov.uk/doc/company/02050399.json');
$json = json_decode($str, true);
$companyname = $json["primaryTopic"]["CompanyName"];
print $companyname;
Output will : ZENITH PRINT (UK) LIMITED
I think you had a mistake at 'primary topic' key. The key-name i saw in the response is 'primaryTopic'. Could you please check again?

Prestashop: notice eval()'d code [8] Array to string conversion

I've been searching through this and other sites and can't solve the notice I got every time I open the back office product page.
Notice on line 279 in file /home/librer16/public_html/tools/smarty/sysplugins/smarty_internal_templatebase.php(157) : eval()'d code
[8] Array to string conversion
Piece of code:
...
else {
//var_dump('renderTemplate', $_template->has_nocache_code, $_template->template_resource, $_template->properties['nocache_hash'], $_template->parent->properties['nocache_hash'], $_output);
//Line 279
if (!empty($_template->properties['nocache_hash']) && !empty($_template->parent->properties['nocache_hash'])) {
// replace nocache_hash
$_output = str_replace("{$_template->properties['nocache_hash']}", $_template->parent->properties['nocache_hash'], $_output);
$_template->parent->has_nocache_code = $_template->parent->has_nocache_code || $_template->has_nocache_code;
}
}
...
The website works, but this notice is very annoying.
Any suggestion to remove the notice?
Try to replace the line with this one:
if (is_array($_template->properties) && !empty($_template->properties['nocache_hash']) && is_array($_template->parent->properties) && !empty($_template->parent->properties['nocache_hash']))
Anyway, if you deactivated Debug Mode warningins won't show anymore.
Good luck.

Undefinet offset error

My code sometimes give code undefinet offset error.
Error:
[03-Sep-2015 13:06:44] NOTICE: "Undefined offset: 6"
File: /home/mdmeds/public_html/includes/pages/game/class.ShowBuildingsPage.php | Line: 111
and
[04-Sep-2015 17:38:57] NOTICE: "Undefined offset: 8"
File: /home/mdmeds/public_html/includes/pages/game/class.ShowBuildingsPage.php | Line: 111
This is the part of the code
$Element = $CurrentQueue[$QueueID - 2][0]; /**this give the error*/
$BuildEndTime = $CurrentQueue[$QueueID - 2][3];
unset($CurrentQueue[$QueueID - 1]);
$NewQueueArray = array();
foreach($CurrentQueue as $ID => $ListIDArray)
{
if ($ID < $QueueID - 1) {
$NewQueueArray[] = $ListIDArray;
} else {
if($Element == $ListIDArray[0] || empty($ListIDArray[0]))
continue;
$BuildEndTime += BuildFunctions::getBuildingTime($USER, $PLANET, $ListIDArray[0]);
$ListIDArray[3] = $BuildEndTime;
$NewQueueArray[] = $ListIDArray;
}
}
I read lot of articles about this kind of errors but i do not know how to fix my code. Can someone help me please ?
You are trying to play with indexes that you are not sure they even exist...
things like
$CurrentQueue[$QueueID - 2]
is a guess... Get to find another way..
In this piece of code $CurrentQueue[$QueueID - 2][0], the key is generated dynamically based on $QueueID. WHen you get the error, it means that the specified key is not available in the array $CurrentQueue.
To avoid such run time exceptions, you can do something like this
if (!empty($CurrentQueue[$QueueID - 2])) {
// the actual functionality goes here.
}

Call to undefined method stdClass

I am occasionally getting the PHP Fatal error: Call to undefined method stdClass::transition() in agent.php on line 25 (I marked line 25 in the code). This code is called often, so struggling to see why it is happening.
Here is the snippet of agent.php that calls the
function agent_exam_complete($exam){
$ce = $exam->educational();
$ce->exam_id = $exam->exam_id;
$ce->exam_grade = $exam->score;
$ce->exams_remaining -= 1;
$ce->exam_received_date = sql_now();
if($exam->status()=='passed'){
$ce->transition('passed');
}elseif($ce->exams_remaining <= 0){
$ce->transition('failed');
}
$ce->save();
if($ce->is_certification_completed($ce->certification_id, $ce->client_no)){
agent_certification_complete($ce->certification_id, $ce->client_no);
}
}
function agent_certification_complete($certification_id, $client_no){
$ce = ClientPurchase::find('first', array('conditions' => "certification_id = '$certification_id' and is_certification = 1 and client_no='$client_no'"));
$ce->certification_date = date('Y-m-d');
$ce->transition('passed'); **//Line 25**
$ce->save();
}
transition() is defined in another file and is called often. I've included a little bit of it's code just for flavor.
function transition($event_tag){
$old_status = $this->status;
$next_status = $this->next_status_for_transition($event_tag);
if($next_status==''){
return; }
$this->status = $next_status;
My question is, why am I only getting this error periodically and not all the time? What can I do to eliminate the error and subsequent blank screen for my clients? I've only noticed that it is happening to those with Firefox or Chrome.
Thanks in advance,
Jim
The object $ce that contains the function is being generated multiple times. I suppose this is so transition is customized for whatever object is called.
Why not create another object for re-useable functions? Consider expanding the function so that it is compatible with all objects that would use it.
$my = new functionClass;
class functionClass
{
function transition()
{
$old_status = $this->status;
$next_status = $this->next_status_for_transition($event_tag);
if($next_status==''){
return; }
$this->status = $next_status;
}
}
$my->transition( 'passed' );
Something like that would cut down on unpredictability and I believe may solve your problem.
Try this little snippet of code to see whats going on:
$ce = false;
$ce->certification_date = date('Y-m-d');
var_dump($ce);
In this case $ce get cast to an object of stdClass when you try to set a property (certification_date).
Now your code:
function agent_certification_complete($certification_id, $client_no){
$ce = ClientPurchase::find('first', array('conditions' => "certification_id = '$certification_id' and is_certification = 1 and client_no='$client_no'"));
//$ce is probably false or null
//it gets cast to a stdClass object
$ce->certification_date = date('Y-m-d');
//stdClass does not have a transition method; ERROR
$ce->transition('passed'); **//Line 25**
$ce->save();
}
So in your code, if find() is returning null or false, or maybe some other choice values, $ce gets cast to a stdClass object on the next line. Then that stdClass object does not have a transition() method so you get an error.
To fix this, either adjust your find method or check its return value and handle accordingly.
As to it happening only in certain browser, I think thats a false conclusion. If find() is calling a query, it probably only happens at certain times depending on the result of that query.

Error with printing min and max from array PHP

I have a cron that pulls an xml api from a gaming website.
Cron then tears the data apart and places the information into the proper section of database. The code was written by someone else in 2010 or 2011. I have been trying to bread new life to old script since orignal writer has not kept the code up to date. When i run my cron i recieve the following error.
key1
Warning: min() [function.min]: Array must contain at least one element in /home3/banumren/public_html/ratter/ratter/cron.php on line 95
Warning: max() [function.max]: Array must contain at least one element in /home3/banumren/public_html/ratter/ratter/cron.php on line 95
[ 0 ] (0 %) - 0 / 0 (beforeRefID: )
* [cachedUntil=2014-05-15 01:19:46 (time-api-taken: 2014-05-15 01:04:46]) ]
wallet.dates = ( to )
The line in question :
<br> * wallet.dates = ( ".$dates1[ min($dates) ]." to ".$dates1[ max($dates) ]." ) \n<br>\n
The whole section of code is as follows.
}
$cachedUntil = (string)$wallet_xml->cachedUntil;
$currentTime = (string)$wallet_xml->currentTime;
print "<b>".$corpName." [ $corpId ] ($corpTax %) "." - $add_wallet_rows / $cnt (beforeRefID: {$beforeRefID}) </b>
<i> <br> * [cachedUntil={$cachedUntil} (time-api-taken: {$currentTime}]) ]
<br> * wallet.dates = ( ".$dates1[ min($dates) ]." to ".$dates1[ max($dates) ]." ) \n<br>\n
</i> ";
$ret = array(
'min' => null, //#min( $RefIDs ) ,
'max' => null, //#max( $RefIDs ) ,
'cnt' => count($RefIDs) ,
'currentTime' => (string)$wallet_xml->currentTime ,
'cachedUntil' => $cachedUntil ,
);
if( $ret['cnt'] ) {
$ret['min'] = min( $RefIDs );
$ret['max'] = max( $RefIDs );
}
return $ret;
}
Any ideas as to what could be causing the error? It seems the cron is pulling the api as it has the time values for cached until and current time. The code worked without issues in 2011, Im a novice at php and not sure if there have been any changes to php in the past few years.
could this be the culprit?
$cnt = 0;
$RefIDs = null;
$dates = $dates1 = array();
foreach( (array)#$xml['row'] as $row ) {
$cnt++;
Removed (array) and no longer receive the error. Now on to another line. at line 180 of 202 so hopefully will have it bug free soon.
Error at line 180 was a missing function from function php.
[14-May-2014 21:33:50] PHP Fatal error: Call to undefined function clear_directory_files_older()
Fixed the error by adding code below to functions.php
function clear_directory_files_older($directory,$older_sec,$ext='*') {
$glob = $directory."*.{$ext}";
$removed = 0;
$array = glob( $glob );
foreach( $array as $file ) {
$filemtime = filemtime($file);
if( $filemtime < ( time()-$older_sec ) ) {
// print "\n<br>OLD => ".( $file ); print "<br>".date('r',$filemtime);
#unlink( $file );
$removed++;
} else {
// print "\n<br>NEW => ".( $file );
}
}
return $removed;
In fixing the new error on 180 the original error returned on line 95
After more searching I walked into the cache folder to have a look around. Seems the issue with the error is the API on the website has changed so much i was not pulling any valid data. After update to the API address cron is now pulling data and updating the cache files correctly. Error no longer occurs.

Categories