I am trying to access OpenStreetMap data using PHP, but I cannot find any clear answers on how to do so. The URL I am trying to pull data from works when I search it in the browser.
Here is the URL I am trying: https://nominatim.openstreetmap.org/search?q=jacksonville,florida&format=json
And this is how I am trying to access it in my PHP file, but it always returns nothing.
$search_url = "https://nominatim.openstreetmap.org/search?q=jacksonville,florida&format=json";
$json = file_get_contents($search_url);
print_r($json);
echo "json=" . $json;
$decoded = json_decode($json, true);
$lat = $decoded[0]["lat"];
$lng = $decoded[0]["lon"];
echo " latitude=".$lat . " -----" . "longitude=".$lng;
How can I fix this? My end goal is to simply get the latitude and longitude of a city, state.
I suspect that the api is refusing to serve a request without a valid User-Agent and http referrer header, try setting this and it should work, for example:
<?php
$search_url = "https://nominatim.openstreetmap.org/search?q=jacksonville,florida&format=json";
$httpOptions = [
"http" => [
"method" => "GET",
"header" => "User-Agent: Nominatim-Test"
]
];
$streamContext = stream_context_create($httpOptions);
$json = file_get_contents($search_url, false, $streamContext);
print_r($json);
echo "json=" . $json;
$decoded = json_decode($json, true);
$lat = $decoded[0]["lat"];
$lng = $decoded[0]["lon"];
echo " latitude=".$lat . " -----" . "longitude=".$lng;
I am developing a simple PHP app which takes
business name,
business address
and business phone from user and then checks if that business is listed in Google or not and
Also compares the business name, address and phone returned by Google against the search terms.
The result I want to display whether the information found in Google is accurate or whether something is different or missing. Something similar as this site does
What I have tried:
I have tried to scrape page with phpQuery library but it does not include that part(which is circled in image below).
$buss_name = $_GET['business_name'];
$link = "https://www.google.com/search?q=" . urlencode($buss_name) . "&rct=j";
$resp_html = file_get_contents($link, false);
$resp_html = phpQuery::newDocumentHTML($resp_html);
echo $resp_html;
echo pq("div.kno-ecr-pt.kno-fb-ctx._hdf",$resp_html)->text();
Reason is that it is loaded via some sort of AJAX call.
I also tried this web service by google
http://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=don%20jayne%20&%20assoc
But this also do not include that part I require.
Long story short >>>
Please tell me is there any API or whatever is available which checks for a business listed on Google or not?
probably you wont need this anymore but I will reply your post just for future reference.
One of the ways to check if a business is on google or not, is to check the google places api (documentation). You can preform a search and then check the results for the business you are looking for. Something like this:
$params = array(
'query' => 'mindseo',
'key' => "XXXXXXXXXXXXXXXXXXX");
$service_url = 'https://maps.googleapis.com/maps/api/place/textsearch/json';
//do the request
$placesSearch = request( $service_url, $params );
//print the result
print_r($placesSearch);
//loop the results
if ( count( $placesSearch['results'] ) >= 1 ) {
$params = array(
'placeid' => $placesSearch['results'][0]['place_id'],
'key' => "AIzaSyAc73-uGCLLIuN3Bb2idOwRbLBzoaTmPHI");
$service_url = 'https://maps.googleapis.com/maps/api/place/details/json';
$placeData = request( $service_url, $params );
//echo the place data
echo '//Place ID#'.$params['placeid'].' DATA -----------------------';
print_r($placeData);
}
//function to make the request
function request( $googleApiUrl, $params) {
$dataOut = array();
$url = $googleApiUrl . '?' . http_build_query($params);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$dataOut = json_decode(curl_exec($ch), true);
curl_close($ch);
return $dataOut;
}
I am developing an android app where I have to get the user's speed and match it with the speedlimit of the road in order to see how he/she is driving.
I am using Open Street Maps to get the road speed limit. But, I'm having problem in getting the tag 'max-speedlimit' which gives the speed limit of the road. Below given php code I am using to get the latitude and longitude from the app and then finding the speed limit. I am having hardtime getting the speedlimit. As there are so many tags in the response from the OSM, I only want to get the max-speed tag's value
Thank you so much!
<?php
$lat = isset($_POST['lat']) ? floatval($_POST['lat']) : "";
$lng = isset($_POST['lng']) ? floatval($_POST['lng']) : "";
$latm = -0.00015 + $lat;
$latp = 0.00015 + $lat;
$lngm = -0.00015 + $lng;
$lngp = 0.00015 + $lng;
$json_url = 'http://overpass.osm.rambler.ru/cgi/interpreter';
$data = '<query type="way"> <bbox-query s="' . $lngm . '" w="' . $latm . '" n="' . $lngp . '" e="' . $latp . '"/> <!--this is auto-completed with the current map view coordinates.--> </query> <print/>';
$ch = curl_init( $json_url );
$options = array(
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => $data,
CURLOPT_RETURNTRANSFER => true,
);
curl_setopt_array( $ch, $options );
$result = curl_exec($ch);
//CONVERT THE RESPONSE IN STRING AND GET THE MAXSPEED TAG VALUE ONLY!
I am trying to programatically perform a search on Microsoft Bing search engine.
Here is my understanding:
There was a Bing Search API 2.0 , which will be replaced soon (1st Aug 2012)
The new API is known as Windows Azure Marketplace.
You use different URL for the two.
In the old API (Bing Search API 2.0), you specify a key (Application ID) in the URL, and such key will be used to authenticate the request. As long as you have the key as a parameter in the URL, you can obtain the results.
In the new API (Windows Azure Marketplace), you do NOT include the key (Account Key) in the URL. Instead, you put in a query URL, then the server will ask for your credentials. When using a browser, there will be a pop-up asking for a/c name and password. Instruction was to leave the account name blank and insert your key in the password field.
Okay, I have done all that and I can see a JSON-formatted results of my search on my browser page.
How do I do this programmatically in PHP? I tried searching for the documentation and sample code from Microsoft MSDN library, but I was either searching in the wrong place, or there are extremely limited resources in there.
Would anyone be able to tell me how do you do the "enter the key in the password field in the pop-up" part in PHP please?
Thanks alot in advance.
Documentation for new services can get a bit interesting - especially in the rabbit-warren of MSDN. The most clear explanation I can find is on the Migration Guide from this Bing Search API page. Best of all the migration guide has a nice simple example in PHP towards the end.
EDIT: Alright, the migration guide is a starting point, but it isn't the best example. Here are two methods that work for me (no proxy, firewalls etc. interfering):
Using file_get_contents
Note: 'allow_url_fopen' needs to be enabled for this to work. You can use ini_set (or change php.ini etc.) if it isn't.
if (isset($_POST['submit']))
{
// Replace this value with your account key
$accountKey = 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=';
$ServiceRootURL = 'https://api.datamarket.azure.com/Bing/Search/';
$WebSearchURL = $ServiceRootURL . 'Web?$format=json&Query=';
$cred = sprintf('Authorization: Basic %s',
base64_encode($accountKey . ":" . $accountKey) );
$context = stream_context_create(array(
'http' => array(
'header' => $cred
)
));
$request = $WebSearchURL . urlencode( '\'' . $_POST["searchText"] . '\'');
$response = file_get_contents($request, 0, $context);
$jsonobj = json_decode($response);
echo('<ul ID="resultList">');
foreach($jsonobj->d->results as $value)
{
echo('<li class="resultlistitem"><a href="'
. $value->URL . '">'.$value->Title.'</a>');
}
echo("</ul>");
}
Using cURL
If cURL is installed, which is normal these days:
<?php
$query = $_POST['searchText'];
$accountKey = 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA';
$serviceRootURL = 'https://api.datamarket.azure.com/Bing/Search/';
$webSearchURL = $serviceRootURL . 'Web?$format=json&Query=';
$request = $webSearchURL . "%27" . urlencode( "$query" ) . "%27";
$process = curl_init($request);
curl_setopt($process, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($process, CURLOPT_USERPWD, "$accountKey:$accountKey");
curl_setopt($process, CURLOPT_TIMEOUT, 30);
curl_setopt($process, CURLOPT_RETURNTRANSFER, TRUE);
$response = curl_exec($process);
$response = json_decode($response);
echo "<ol>";
foreach( $response->d->results as $result ) {
$url = $result->Url;
$title = $result->Title;
echo "<li><a href='$url'>$title</a></li>";
}
echo "</ol>";
?>
[WTS] changed SearchWeb to Search.
None of the above worked for me. Im running MAMP, this may be relevant. Try the below:
$accountKey = '=';
function sitesearch ($query, $site, $accountKey, $count=NULL){
// code from http://go.microsoft.com/fwlink/?LinkID=248077
$context = stream_context_create(array(
'http' => array(
'request_fulluri' => true,
'header' => "Authorization: Basic " . base64_encode($accountKey . ":" . $accountKey)
)
));
$ServiceRootURL = 'https://api.datamarket.azure.com/Data.ashx/Bing/Search/v1/News?Market=%27en-GB%27&';
$WebSearchURL = $ServiceRootURL . '$format=json&Query=';
$request = $WebSearchURL . urlencode("'$query'"); // note the extra single quotes
if ($count) $request .= "&\$top=$count"; // note the dollar sign before $top--it's not a variable!
return json_decode(file_get_contents($request, 0, $context), true);
}
$q = "query";
if ($q){
// get search results
$articles = sitesearch ($q, $_SERVER['HTTP_HOST'], $accountKey , 100);
foreach($articles['d']['results'] as $article) {
echo " <p>".$article['Title'].'</p>';
echo " <p>".$article['Description'].'</p>';
echo " <p>".$article['Source'].'</p>';
echo " <p>".strtotime($article['Date']).'</p>';
}
}
FROM:
http://bililite.com/blog/2012/06/05/new-bing-api/
you can use bellow code to get bing search results
$acctKey = 'Your account key here';
$rootUri = 'https://api.datamarket.azure.com/Bing/Search';
$query = 'Kitchen';
$serviceOp ='Image';
$market ='en-us';
$query = urlencode("'$query'");
$market = urlencode("'$market'");
$requestUri = "$rootUri/$serviceOp?\$format=json&Query=$query&Market=$market";
$auth = base64_encode("$acctKey:$acctKey");
$data = array(
'http' => array(
'request_fulluri' => true,
'ignore_errors' => true,
'header' => "Authorization: Basic $auth"
)
);
$context = stream_context_create($data);
$response = file_get_contents($requestUri, 0, $context);
$response=json_decode($response);
echo "<pre>";
print_r($response);
echo "</pre>";
http://www.guguncube.com/2771/python-using-the-bing-search-api
it contains python code to query the bing and this is according to latest new API (Windows Azure Marketplace)
# -*- coding: utf-8 -*-
import urllib
import urllib2
import json
def main():
query = "sunshine"
print bing_search(query, 'Web')
print bing_search(query, 'Image')
def bing_search(query, search_type):
#search_type: Web, Image, News, Video
key= 'YOUR_API_KEY'
query = urllib.quote(query)
# create credential for authentication
user_agent = 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; Trident/4.0; FDM; .NET CLR 2.0.50727; InfoPath.2; .NET CLR 1.1.4322)'
credentials = (':%s' % key).encode('base64')[:-1]
auth = 'Basic %s' % credentials
url = 'https://api.datamarket.azure.com/Data.ashx/Bing/Search/'+search_type+'?Query=%27'+query+'%27&$top=5&$format=json'
request = urllib2.Request(url)
request.add_header('Authorization', auth)
request.add_header('User-Agent', user_agent)
request_opener = urllib2.build_opener()
response = request_opener.open(request)
response_data = response.read()
json_result = json.loads(response_data)
result_list = json_result['d']['results']
print result_list
return result_list
if __name__ == "__main__":
main()
Don't forget to put this:
base64_encode("ignored:".$accountKey)
instead of:
base64_encode($accountKey . ":" . $accountKey)
Here is a working example of the Search API just replace "XXXX" with your access key. Even I wasted quite a few hours trying to get it to work using cURL but it was failing because of "CURLOPT_SSL_VERIFYPEER" on local :( - so make sure your cURL opts are set properly.
$url = 'https://api.datamarket.azure.com/Bing/Search/Web?Query=%27xbox%27';
$process = curl_init($url);
curl_setopt($process, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($process, CURLOPT_USERPWD, base64_encode("username:XXXX"));
curl_setopt($process, CURLOPT_TIMEOUT, 30);
curl_setopt($process, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($process, CURLOPT_SSL_VERIFYPEER, false);
$response = curl_exec($process);
# Deliver
return $response;
# Have a great day!
curl_close($process);
Here is the example of how to call Bing/Azure API using Unirest library.
require_once '/path/to/unirest-php/lib/Unirest.php';
$accountKey = "xxx";
$searchResults = Unirest::get("https://api.datamarket.azure.com/Bing/Search/v1/Composite",
array(),
array(
'Query' => '%27Microsoft%27',
'Sources' => '%27web%2Bimage%2Bvideo%2Bnews%2Bspell%27',
'$format' => 'json',
), $accountKey, $accountKey
);
// Results are here:
$objectArray = $searchResults->body->d->results;
$rawJson = $searchResults->raw_body;
You can omit Source parameter by defining it in the URL: https://api.datamarket.azure.com/Bing/Search/v1/Webor https://api.datamarket.azure.com/Bing/Search/v1/Image
Note: parameters in request URL are case-sensitive. For Bing they start with a capital letter.
I am experimenting with the Endicia shipping label server. The sample code below allows me to get a USPS label from their test server. How would I display the image that is being returned. Right now the print_r function (if un-commented out) does print out the array contents of what appears to be an image.
<?php
$strGetLabelURL = "https://www.envmgr.com/LabelService/EwsLabelService.asmx/GetPostageLabelXML";
$request = '<LabelRequest ImageFormat="GIF" Test="YES">
<RequesterID>abcd</RequesterID>
<AccountID>123456</AccountID>
<PassPhrase>samplePassPhrase</PassPhrase>
<MailClass>FIRST</MailClass>
<DateAdvance>0</DateAdvance>
<WeightOz>1</WeightOz>
<Stealth>FALSE</Stealth>
<Services InsuredMail="OFF" SignatureConfirmation="OFF" />
<Value>0</Value>
<Description>Sample Label</Description>
<PartnerCustomerID>12345ABCD</PartnerCustomerID>
<PartnerTransactionID>6789EFGH</PartnerTransactionID>
<ToName>Ben Franklin</ToName>
<ToCompany>United States Postal Service</ToCompany>
<ToAddress1>12345 Main Street</ToAddress1>
<ToCity>Camas</ToCity>
<ToState>WA</ToState>
<ToPostalCode>98607</ToPostalCode>
<ToPhone>2025551212</ToPhone>
<FromName>Technical Support</FromName>
<FromCompany>DYMO Endicia</FromCompany>
<ReturnAddress1>385 Sherman Ave.</ReturnAddress1>
<FromCity>Palo Alto</FromCity>
<FromState>CA</FromState>
<FromPostalCode>94306</FromPostalCode>
<FromZIP4>1864</FromZIP4>
<FromPhone>8005763279</FromPhone>
</LabelRequest>';
$params = array('http' => array(
'method' => 'POST',
'content' => 'labelRequestXML='.$request,
'header' => 'Content-Type: application/x-www-form-urlencoded'));
$ctx = stream_context_create($params);
$fp = fopen($strGetLabelURL, 'rb', false, $ctx);
if (!$fp)
{
print "Problem with $strGetLabelURL";
}
$response = stream_get_contents($fp);
if ($response === false)
{
print "Problem reading data from $url, $php_errormsg";
}
print_r($response);
?>
You have to load the XML, extract the image data, then put it in an image:
$sxml = Simplexml_load_string( $response );
echo '<img src="data:image/gif;base64,' . $sxml->Base64LabelImage . '">';
I don't know about Endicia solution but I think it's quite similar to UPS.
From the XML you send one can see that you ask for the label in GIF format.
I suppose that in the response you have an element named <LabelImage> or something similar. You need to extract the value that is between the opening and the closing tag and use below to print it on your browser:
echo '<img src="data:image/gif;base64,' . $value . '" alt="" />';