cache googlemaps geocoding results but my code is broken - php

I posted this question last night but I worded it wrong and didn't explain correctly. I am trying to cache googlemaps geocoding results for use in a firefighting mapping thing I have made and I am getting close to google's limits hence the need to cache the results. Help!
The code below kinda works however it creates a new sql record each time the code runs regardless of whether the address is already in the database. It seems to only call google once then saves the data, it then loads the data from the database ok and it looks like the rest works but I just can't see where I am going wrong.. As I said it creates a new record each and everytime the code runs and I would end up with a database full of the same identical records. My brain hurts but I really need to get this working so I can continue to help fire trucks to fires. :)
Oh, I am using the geocoding results on googlemaps (as permitted by the T&C) and this code is really only to get it working. I hope that makes sense and I hope someone can help... Thanks :)
<?php
$jobadd = "1000 BURWOOD HWY, BURWOOD";
// connect to the database
include('connect-db.php');
// get results from database and find needle
$result = mysql_query("SELECT * FROM geocache")
or die(mysql_error());
while($row = mysql_fetch_array( $result ))
{
$needle = '' . $row['address'] . '';
if (strpos($jobadd,$needle) !== false)
{
$status = "CACHED";
$latitude = '' . $row['latitude'] . '';
$longitude = '' . $row['longitude'] . '';
}
else
{
$status = "GOOGLE";
$address2 = "$jobadd, Victoria, Australia";
define("MAPS_HOST", "maps.google.com");
$base_url = "http://" . MAPS_HOST . "/maps/api/geocode/xml";
$request_url = $base_url . "?address=" . urlencode($address2) ."&sensor=false";
$xml = new SimpleXMLElement(file_get_contents($request_url));
$latitude = $xml->result->geometry->location->lat;
$longitude = $xml->result->geometry->location->lng;
// save the data to the database
mysql_query("INSERT geocache SET address='$jobadd', latitude='$latitude', longitude='$longitude' ")
or die(mysql_error());
}
}
echo $status;
echo '<BR>';
echo $jobadd;
echo '<BR>';
echo 'LAT:';
echo $latitude;
echo '<BR>';
echo 'LON:';
echo $longitude;
?>

Have you tried to output the result of strpos? The logic does not look incorrect. The issue is in the if condition. What do the records look like in the DB?

Related

How do you display the stream name? [ICECAST]

I took a part of PHP code from a different Stackoverflow question, and it works perfectly.
<?php header>
//Display IceCast Server Stats
$server = "***********"; //IP (x.x.x.x or domain name)
$iceport = "8070"; //Port
$iceurl = "live"; //Mountpoint
$online = "<font color=green><b>ONLINE</b> </font><br />";
$offline = "<font color=red><b>OFFLINE</b></font><br />";
if($fp = #fsockopen($server, $iceport, $errno, $errstr, '1')) {
fclose($fp);
$ice_status=$online;
echo "<p><b>DJ:</b> $ice_status";
$stats = file("http://" . $server . ":" . $iceport . "/status2.xsl");
$status = explode(",", $stats[5]);
$artist = explode("-", $status[5]);
echo " " . $artist[1];
echo " - ";
echo " " . $artist[2];
echo "<br />";
// echo "<b>Listeners:</b> <b> " . $status[3] . "</b>";
echo "</p>";
//echo "<br />";
//echo "<p><a href=http://" . $server . ":" . $iceport . "/" . $iceurl . " target=new><b>Listen!</b></a></p>";
} else {
$ice_status=$offline;
echo "<p><b>DJ:</b> $ice_status";
}
?>
<hr />
</center>
I'm trying to add the stream name, which is currently:
echo "DJ: $ice_status";
This displays DJ: ONLINE, but I want it to say DJ: (DJ Name/Stream Name)
I do believe its variables from status2.xsl, but I'm a complete noob at this, and can't seem to figure out how to use it. Could anyone tell me what streamname variable would be?
I was also wondering, is it possible to make it so the "nowplaying.php" refreshes, but my whole web page doesn't? I've tried an iframe, but it makes it look really bad, and has errors.
What my website looks like at the moment: https://i.stack.imgur.com/luc4O.jpg
I'd suggest having a look at TheFineManualâ„¢:
http://icecast.org/docs/icecast-2.4.1/server-stats.html#xslt
Especially the part about status-json.xsl. Make sure you are running an up to date version of Icecast. Icecast is available from all major Linux distributions in up to date packaging. Xiph provides independent packaging, which is useful if there are no up to date packages for a distribution, e.g. shortly after an Icecast release.
status2.xsl was an example file, and a bad one at that. It was removed from newer Icecast versions.

PHP Google API Client v3 get contacts

I still have trouble with the new google_api_client php library. I'm trying to retrieve the user's contacts.
I'm very close to the right solution ... I mean, I just got all the results but a can't parse it.
Probably it's because I'm not strong with XML parser. After tests and tests ... I get this solution (based on the example file by Google):
...
$req = new apiHttpRequest("https://www.google.com/m8/feeds/contacts/default/full");
$val = $client->getIo()->authenticatedRequest($req);
$response = simplexml_load_string($val->getResponseBody());
foreach($response->entry as $entry)
{
$child = $entry->children("http://schemas.google.com/g/2005");
$mail_info = $child->attributes();
}
...
In the $response I can get the title field where my contact's full name is stored, and in the $mail_info a got an object where i see the address field when I get the email address.
It's SAD and UGLY solution ... what if I want the company name, address ... phone numbers ... photos. Where are all these informations.
How can I use the Google response in a great and clean solution?
Anyone can give me some help.
Bye
What helped me was requesting JSON instead of XML. Try adding ?alt=json to the end of the URL in the request you make to google.
$req = new apiHttpRequest("https://www.google.com/m8/feeds/contacts/default/full?alt=json");
$val = $client->getIo()->authenticatedRequest($req);
$string = $val->getResponseBody();
$phparray = json_decode($string);
Certainly not child's play to get what you want but working with php arrays is probably easier.
For completeness this is the google contacts php example that we both probably found that helped us:
https://code.google.com/p/google-api-php-client/source/browse/trunk/examples/contacts/simple.php
EDIT:
Here is another link that might help. In the comments it describes a cleaner of accessing contact's data using JSON.
http://25labs.com/import-gmail-or-google-contacts-using-google-contacts-data-api-3-0-and-oauth-2-0-in-php/
$url = 'https://www.google.com/m8/feeds/contacts/default/full?max-results='.$max_results.'&alt=json&v=3.0&oauth_token='.$accesstoken;
$xmlresponse = curl_file_get_contents($url);
$temp = json_decode($xmlresponse,true);
foreach($temp['feed']['entry'] as $cnt) {
echo $cnt['title']['$t'] . " --- " . $cnt['gd$email']['0']['address'] . "</br>";
}
and
$url = 'https://www.google.com/m8/feeds/contacts/default/full?max-results='.$max_results.'&alt=json&v=3.0&oauth_token='.$accesstoken;
$xmlresponse = curl_file_get_contents($url);
$temp = json_decode($xmlresponse,true);
foreach($temp['feed']['entry'] as $cnt) {
echo $cnt['title']['$t'] . " --- " . $cnt['gd$email']['0']['address'];
if(isset($cnt['gd$phoneNumber'])) echo " --- " . $cnt['gd$phoneNumber'][0]['$t'];
if(isset($cnt['gd$structuredPostalAddress'][0]['gd$street'])) echo " --- " . $cnt['gd$structuredPostalAddress'][0]['gd$street']['$t'];
if(isset($cnt['gd$structuredPostalAddress'][0]['gd$neighborhood'])) echo " --- " . $cnt['gd$structuredPostalAddress'][0]['gd$neighborhood']['$t'];
if(isset($cnt['gd$structuredPostalAddress'][0]['gd$pobox'])) echo " --- " . $cnt['gd$structuredPostalAddress'][0]['gd$pobox']['$t'];
if(isset($cnt['gd$structuredPostalAddress'][0]['gd$postcode'])) echo " --- " . $cnt['gd$structuredPostalAddress'][0]['gd$postcode']['$t'];
if(isset($cnt['gd$structuredPostalAddress'][0]['gd$city'])) echo " --- " . $cnt['gd$structuredPostalAddress'][0]['gd$city']['$t'];
if(isset($cnt['gd$structuredPostalAddress'][0]['gd$region'])) echo " --- " . $cnt['gd$structuredPostalAddress'][0]['gd$region']['$t'];
if(isset($cnt['gd$structuredPostalAddress'][0]['gd$country'])) echo " --- " . $cnt['gd$structuredPostalAddress'][0]['gd$country']['$t'];
echo "</br>";
}

Is there an easier/shorter way to get geographic coordinates from GoogleMaps?

I'm currently using the following method to get coordinates from GoogleMaps.
Can I possibly write this shorter/more efficient?
EDIT 21.06.2013
As of now the old Google Geocoding API is off. This is my modified code that works with the most recent version. I've updated this post, if someone stumbles over it and finds it useful.
public function getGeographicCoordinatesFromGoogle()
{
// create address string
$value = $this->address_line_1 . ' ' .
$this->postal_code . ' ' .
$this->city . ' ' .
$this->country;
$value = preg_replace('!\s+!', '+', $value);
// create request
$request = 'http://maps.googleapis.com/maps/api/geocode/xml?address=' .
$value . '&sensor=false';
// get value from xml request
$xml = file_get_contents($request);
$doc = new \DOMDocument('1.0', 'UTF-8');
#$doc->loadXML($xml);
// fetch result
$result = $doc->getElementsByTagName('lat')->item(0)->nodeValue . ',' .
$doc->getElementsByTagName('lng')->item(0)->nodeValue;
// check result
if (!preg_match('/(-?\d+\.\d+),(-?\d+\.\d+)/', $result) ) {
$result = null;
}
// assign value
$this->setGeographicCoordinates($result);
}
You can use json instead of xml. json is newer, lightweight and object orientated.
I'll recommend you to use http_build_query() instead of trying to build the SearchQuery with Regex. There are other chars which need to be escaped.
This is a quite long method. Maybe it would make sense to have one Class which only handles the communication with GoogleMaps (Class GeoBackend with methods getGeoDataForAddress(), which returns a GeoData-Object, which could be asked for Cordinates etc.)

php xml url's with multiple words

having an annoying issue with getting xml data from a url
if i set "$file_show_title" to a single word (comes from the url passed from another page) then all works fine. if if "$file_show_title" is 2 words (tried encoding the url also) then it failed to find the address.
im not the best at explaining but i hope that this is enough for someone to help me please
thanks
$url = file_get_contents("http://www.thetvdb.com/api/GetSeries.php?seriesname=".$file_show_title);
$xml = simplexml_load_string($url);
$seriesid = $xml->Series[0]->seriesid;
$seriesbanner = $xml->Series[0]->banner;
$seriesname = $xml->Series[0]->SeriesName;
$serieslanguage = $xml->Series[0]->language;
$seriesfist_aired = $xml->Series[0]->FirstAired;
$seriesoverview = $xml->Series[0]->Overview;
echo '<img src="/images/'.$seriesbanner.'">'."<br />";
echo $seriesname."<br />";
echo $seriesid."<br />";
echo $serieslanguage."<br />";
echo $seriesfist_aired."<br />";
echo $seriesoverview."<br />";
What you needed was urlencode Please see http://php.net/manual/en/function.urlencode.php for more information
Example
$url = file_get_contents("http://www.thetvdb.com/api/GetSeries.php?seriesname=" . urlencode("Prison Break"));
Now Use
$url = file_get_contents("http://www.thetvdb.com/api/GetSeries.php?seriesname=" . urlencode($file_show_title));
I hope it helps

Trying to make an function call to an external file with PhP, MySQL using WAMP

I'm sure there is a simple answer to this, but I have been fumbling with everything for almost a week now and surrender. I am trying to build a shopping cart app and every coding solution I build will work when I include the code on the same page, but when I try to use an external page to run the function it does not seem to return the data. I have tried various monitoring techniques to determine what it is happening.
Here is the code for the main page:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Cart Connection</title>
<meta http-equiv="content-type" content="text/html; charset=iso-8859-1" />
</head>
<body>
<p>Will this display?</p>
<p><a href='<?php echo "showCart.php?PHPSESSID=" . session_id() ?>'>View Cart</a></p>
<?php
$Database = "L3TtL2B5DdY";
$Table = "tblProds";
if (isset($_SESSION['curCart']))
$Cart = unserialize($_SESSION['curCart']);
else
{
if (class_exists("shoppingCart"))
{
$Cart = new shoppingCart();
$Cart->setDatabase($Database);
echo ("<p>If statement ran successfully</p>");
}
else
exit("<p>The shoppingCart class is not available!");
}
$Cart->setTable($Table);
$Cart->getProductList();
$_SESSION['curCart'] = serialize($Cart);
?>
<p><a href='<?php echo "showCart.php?PHPSESSID=" . session_id() ?>'>View Cart</a></p>
</body>
</html>
Here is the relevant code on the "shoppingCart.php" page:
<?php
class shoppingCart
{
private $dbConn = "";
private $dbName = "";
private $tableName = "";
private $orders = array();
private $orderTable = array();
function _construct()
{
$this->dbConn = #new mysqli("localhost", "root", "");
if (mysqli_connect_errno())
die("<p>Unable to connect to the database server.</p>" . "<p>Error Code " .
mysqli_connect_errno() . ": " . mysqli_connect_error() . "</p>");
}
public function setDatabase($Database)
{
$this->dbName = $Database;
#$this->dbConn->select_db($this->dbName)
Or die("<p>Unable to select the database.</p>" . "<p>Error code " . mysqli_errno($this->dbConn) .
": " . mysqli_error($this->dbConn) . "</p>");
}
public function setTable($Table)
{
$this->tableName = $Table;
}
public function getProductList()
{
$sqlString = "SELECT prodID, prodName, prodPrice FROM $this->tableName";
#$qryResult = $this->dbConn->query($sqlString)
Or die("<p>Unable to perform the query.</p>" . "<p>Error code " . mysqli_errno($this->dbConn) .
": " . mysqli_error($this->dbConn) . "</p>");
echo "<table width='100%' border='1'>";
echo "<tr><th>Product ID</th><th>Product Name</th><th>Product Price</th><th>Select Item</th></tr>";
$row = $qryResult->fetch_row();
do
{
echo "<tr><td>{$row[0]}</td>";
echo "<td>{$row[1]}</td>";
echo "<td>{$row[2]}</td>";
echo "<td><a href='showCart.php?PHPSESSID=" . session_id() . "&operation=addItem&productID=" . $row[0] .
"'>Add</a></td></tr>";
$row = $qryResult->fetch_row();
} while ($row);
echo "</table>";
}
......
?>
When I try to load the main page it will display the two lines and that is all. I debugged all the errors when I first created the code and thought it would work. When I wrote the original version of this page I put the "connection" code on the same page and the table displayed fine, so I don't know what else it could be.
I installed WAMP on my Windows XP box and it seems to work fine. I haven't touched the configuration files for any of the programs and all my other test code seems to work fine. It is just when I try to contact an external file.
Any help would be greatly appreciated as I think my brain is turning to mush.
Thanks
You probably need to include the ShoppingCart.php file in your main page, so it has the definition of the ShoppingCart class. Try putting at the top of your main page:
<?php require('ShoppingCart.php'); ?>
What I think might be happening is that the cart object is getting unserialised from the Session, but there is no class definition, so it becomes an instance of an incomplete class. When you then call a method on it you are getting a fatal error. What probably doesn't help is that you may not be displaying errors, so the script will just end. You could also try putting at the top of the main page:
<?php ini_set('display_errors', true); ?>
This should make PHP errors get shown.
Edit
It might be worth pointing out that you can't store a database connection in the session. You need to connect to the server / select the database etc. on every request. I don't think your script is currently doing that.
Also, you can store objects in the session without worrying about the serialisation yourself, here is a quick example:
<?php
//include class definition before starting session.
require('ShoppingCart.php');
session_start();
if (!isset($session['cart'])) {
$session['cart'] = new ShoppingCart();
}
$cart = $session['cart'];
//do stuff to cart
$cart->doSomething();
//changes are now saved back to the session when the script is terminated, without you having to do anything.
You need to
include_once("ShoppingCart.php");
Read up on the different ways to include files
http://www.w3schools.com/PHP/php_includes.asp

Categories