I have a question with my Google Maps API. I am using a simple geocoding script to pull a txt/xml file from my server and geocoding the addresses. I have a problem with the addresses coming back as a null value and breaking the script and my database because the coord_lat and coord_long are floats and cannot accept null values.
The error I am receiving is: Warning: file_get_contents(http://maps.google.com/maps/geo?key=AIzaSyBmT9F_ixjLlW8oDiYVqgHqt14a008kXwc&output=xml&q=131+rochestor+ave+039482) [function.file-get-contents]: failed to open stream: HTTP request failed! HTTP/1.0 403 Forbidden in /includes/sfupdate/func.php on line 294 {"status":"Failed","data":"SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'coord_lat' cannot be null"}
ErrorSyntaxError: Unexpected token
Is this a problem with my connection with Google Maps API? I see HTTP Request failed which leads me to believe that I am being rejected and the addresses are turning back a null value because of it. Advice would be appreciated, thank you.
Sorry for posting a new answer, but here is my current geocoding script.
function get_lat_long($address, $zipcode) {
if(strlen($zipcode) == 4){
$zipcode = '0' . $zipcode;
//echo $zipcode . "\n";
}
$apikey = "IzaSyBmT9F_ixjLlW8oDiYVqgHqt14a008kXwc";
$geourl = "http://maps.google.com/maps/geo?key=" . $apikey . "&output=xml&q=" . urlencode($address) . "+" . urlencode($zipcode);
//echo $geourl;
//echo "<br>";
// Grab XML content using $geourl
$context = stream_context_create(array('http' => array('header' => 'Accept: application/xml')));
$xml = file_get_contents($geourl, false, $context);
$xml = simplexml_load_string($xml);
//Parse the lat and long from the XML
$Lat = $xml->results->result->locations->location->displayLatLng->latLng->lat;
//echo $Lat;
$Lng = $xml->results->result->locations->location->displayLatLng->latLng->lng;
//echo $Lng;
//Return
if($Lng && $Lat) {
return array('lat'=>$Lat,
'lng'=>$Lng
);
} else {
return false;
}
}
Related
How can I handle google API errors? For example, the following script will get the screenshot from the website requested:
$api_response = file_get_contents("https://www.googleapis.com/pagespeedonline/v5/runPagespeed?url=" . $websiteURL . "&screenshot=true");
$result = json_decode($api_response, true);
$screenshot1 = $result['lighthouseResult']['audits']['final-screenshot']['details']['data'];
but if the domain doesn't exists google returns this error:
Failed to open stream: HTTP request failed! HTTP/1.1 500 Internal Server Error
How can I handle this error and create a custom error page for that?
My project is on Laravel 8.
You could do it with an if statement
if(($api_response = #file_get_contents("https://www.googleapis.com/pagespeedonline/v5/runPagespeed?url=" . $websiteURL . "&screenshot=true")) !== false) {
//success
$result = json_decode($api_response, true);
$screenshot1 = $result['lighthouseResult']['audits']['final-screenshot']['details']['data'];
}
else{
//do error stuff
}
Help would be appreciated on this. I have a txt/xml list of physical addresses that I pass through a Google Maps geocoding script but have been running into a problem where the address spits out a null value on the coord_lat and my MySQL database rejects this. The error I receive is an HTTP request failed so I believe it is problem where the Google Maps is rejecting my connection and returning a null value which then breaks my script/database. Does anyone have any idea on how to fix this connection and/or add something to the script? I am currently using HostGator as my hosting service.
Warning: file_get_contents(http://maps.google.com/maps/geo?key=AIzaSyBmT9F_ixjLlW8oDiYVqgHqt1888&output=xml&q=xxx+here) [function.file-get-contents]: failed to open stream: HTTP request failed! HTTP/1.0 403 Forbidden in /includes/func.php on line 297
{"status":"Failed","data":"SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'coord_lat' cannot be null"}
ErrorSyntaxError: Unexpected token
function get_lat_long($address, $zipcode) {
if(strlen($zipcode) == 4){
$zipcode = '0' . $zipcode;
//echo $zipcode . "\n";
}
$apikey = "AIzaSyBmT9F_ixjLlW8oDiYVqgHqt1888";
$geourl = "http://maps.google.com/maps/geo?key=" . $apikey . "&output=xml&q=" . urlencode($address) . "+" . urlencode($zipcode);
//echo $geourl;
//echo "<br>";
// Grab XML content using $geourl
$context = stream_context_create(array('http' => array('header' => 'Accept: application/xml')));
$xml = file_get_contents($geourl, false, $context);
$xml = simplexml_load_string($xml);
//Parse the lat and long from the XML
$Lat = $xml->results->result->locations->location->displayLatLng->latLng->lat;
//echo $Lat;
$Lng = $xml->results->result->locations->location->displayLatLng->latLng->lng;
//echo $Lng;
//Return
if($Lng && $Lat) {
return array('lat'=>$Lat,
'lng'=>$Lng
);
} else {
return false;
}
}
use google maps v3 what you are using is v2 i think and its not working anymore
$Address = urlencode($Address);
$url='http://maps.googleapis.com/maps/api/geocode/json?address=egypt&sensor=false';
$source = file_get_contents($url);
$obj = json_decode($source);
$lat = $obj->results[0]->geometry->location->lat;
$lng = $obj->results[0]->geometry->location->lng;
I am trying to use AlchemyAPI's php sdk. I am running the same example given on their Github page.
But when I try to run the example, I get this error message-
Warning: fclose() expects parameter 1 to be resource, boolean given in C:\wamp\www\twitter-analysis\alchemyapi.php on line 261
What could be the reason? In alchemyapi.php, this is where the warning is occuring-
private function analyze($url, $params) {
//Insert the base URL
$url = $this->_BASE_URL . $url;
//Add the API Key and set the output mode to JSON
$url = $url . '?apikey=' . $this->_api_key . '&outputMode=json';
//Add the remaining parameters
foreach($params as $key => $value) {
$url = $url . '&' . $key . '=' . $value;
}
//Create the HTTP header
$header = array('http' => array('method' => 'POST', 'Content-type'=> 'application/x-www-form-urlencoded'));
//Fire off the HTTP Request
try {
$fp = #fopen($url, 'rb',false, stream_context_create($header));
$response = #stream_get_contents($fp);
fclose($fp);
return json_decode($response, true);
} catch (Exception $e) {
return array('status'=>'ERROR', 'statusInfo'=>'Network error');
}
}
}
fopen() returns the resource if it succeeds, and false if it didn't work. The most likely case for the fopen to not work is if the path is invalid or if you don't have access to the resource.
A similar question was asked here: https://stackoverflow.com/questions/18636680/php-warning-fclose-expects-parameter-1-to-be-resource-boolean-given
Try to test on live server.
My experience it gives error in local server where works in live server.
So i am trying to parse data from an XML url and insert it into a table using php, which can be seen here, (please keep in mind there are more products than displayed on this page, i am not trying to get it for just this Product,the code below shows how i am parsing all products) but i keep getting the following errors:
[EDITED]
class DataGrabber {
//The URL where data will be extracted from, which is an XML file
protected $URL = "http://json.zandparts.com/api/category/GetCategories/44/EUR/";
public function call_api($data) {
if(count($data) == 0) return array();
$jsondata = array();
foreach($data as $entry){
$url = $this->URL . $entry['model'] . "/" . urlencode($entry['family']) . "/" . urlencode($entry['cat']) . "/" . $entry['man'] . "/null";
$json = file_get_contents($url);
$data = json_decode($json, true);
if(!empty($data['Products'])){
foreach ($data['Products'] as $id => $product) {
$jsonentry = array(
'productnumber' => $id,
'partnumber' => $product['strPartNumber'],
'description' => $product['strDescription'],
'manu' => $product['Brand']
);
$jsondata[] = $jsonentry;
}
}
}
return $jsondata;
}
}
[NEW ERRORS]
So i have fixed the error:
PHP Warning: file_get_contents(http://json.zandparts.com/api/category/GetCategories/44/EUR/ET10B/E Series/AC Adapter/Asus/null): failed to open stream: HTTP request failed! HTTP/1.1 400 Bad Request
in /home/svn/dev.comp/Asus.php on line 82
by using urlencode as shown in my code above
This warning below isnt finding the values for the url:
PHP Warning: file_get_contents(http://json.zandparts.com/api/category/GetCategories/44/EUR///04G265003580/Asus/null): failed to open stream: HTTP request failed! HTTP/1.1 404 Not Found
as you can see after, 44/EUR there are three forward slashes with no data?? How would i resolve this??
The remote server appears to use the Accept HTTP header to choose the output format. With PHP default options it sends back JSON instead of XML:
<?php
echo file_get_contents('http://json.zandparts.com/api/category/GetCategories/44/EUR/ET10B/E%20Series/AC%20Adapter/Asus/null');
... prints:
{"Categories":[{"Brand":null,"Fami...
To specify an Accept header you need to retrieve the data with some other function, e.g.:
<?php
$context = stream_context_create(
array(
'http' => array(
'header' => "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\r\n",
)
)
);
echo file_get_contents('http://json.zandparts.com/api/category/GetCategories/44/EUR/ET10B/E%20Series/AC%20Adapter/Asus/null', false, $context);
... prints:
<?xml version="1.0" encoding="utf-8"?><ProductCategory ...
Tweak it to your exact needs, I just copied the header from my browser.
Here's a code snippet that shows you how to get the values for strPartNumber, strDescription and Brand for all the products in that JSON data:
<?php
$url = 'http://json.zandparts.com/api/category/GetCategories/44/EUR/ET10B/E%20Series/AC%20Adapter/Asus/null';
$json = file_get_contents($url);
// Decode the JSON data as a PHP array
$data = json_decode($json, true);
if (!empty($data['Products'])) {
foreach ($data['Products'] as $id => $product) {
echo "Product #{$id}\n";
echo "Part number: {$product['strPartNumber']}\n";
echo "Description: {$product['strDescription']}\n";
echo "Brand: {$product['Brand']}\n\n";
}
}
Output:
Product #0
Part number: 04G265003580
Description: POWER ADAPTER 65W19V 3PIN
Brand: Asus
Product #1
Part number: 14G110008340
Description: POWER CORD 3P L:80CM,TW(B)
Brand: Asus
I have been trying to retrieve the following data using the following code in php:
$fql_query='SELECT%20name,%20birthday_date,%20sex,%20current_location.name,%20email%20FROM%20user%20WHERE%20uid=me()';<br>
// Run fql query<br>
$fql_query_url = 'https://graph.facebook.com/'
. '/fql?q='.$fql_query
. '&' . $access_token;<br>
$fql_query_result = file_get_contents($fql_query_url);<br>
$fql_query_obj = json_decode($fql_query_result, true);<br>
Warning:
file_get_contents(https://graph.facebook.com//fql?q=SELECT%20name,%20birthday_date,%20sex,%20current_location.name,%20email%20FROM%20user%20WHERE%20uid=me()&access_token=)
[function.file-get-contents]: failed to open stream: HTTP request
failed! HTTP/1.0 400 Bad Request in on line 223
I believe the following error is because the user has not provided current location in the profile. If I add the data the code works fine. How do I catch that error?
"[function.file-get-contents]: failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request in on line 223"
Would tell you that as the function is failing, it can be tested logically for a result e.g.
$fql_query='SELECT%20name,%20birthday_date,%20sex,%20current_location.name,%20email%20FROM%20user%20WHERE%20uid=me()';
// Check FQL query
$fql_query_url = 'https://graph.facebook.com/'
. '/fql?q='.$fql_query
. '&' . $access_token;<br>
// First logically check the result, TRUE: Result is passed to $fql_query_result.
// FALSE: $flq_query_result = 0 or false.
$fql_query_result = file_get_contents($fql_query_url) ? file_get_contents($fql_query_url) : 0;
// Only json_decode the result if it was valid.
$fql_query_obj = (!$fql_query_result == 0) ? json_decode($fql_query_result, true) : "FQL was not a valid query";