How to develop user defined menu on wechat - php

here is my sample code. my developer mode is already enabled but there is no menu tabs options.
you can also add me on wechat so I can elaborate my problems in this matter, here is my wechat ID VinceZen. I badly need some help guys. Thank you in advance.
<?php
$data[] = '772134292672v';
$data[] = $_GET['timestamp'];
$data[] = $_GET['nonce'];
asort($data);
$strData = '';
$d = '';
$authString = '';
foreach($data as $d)
{
$authString .= $d;
}
//verify the signature
if(sha1($authString) == $_GET['signature'])
{
//check the echostr
if(!empty($_GET['echostr']))
{
echo $_GET['echostr'];
die();
}
else
{
//logic
//Getting access_token from customize menus
static function get_access_token($appid,$secret){
$url="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$appid."&secret=".$secret;
$json=http_request_json($url);//here cannot use file_get_contents
$data=json_decode($json,true);
if($data['access_token']){
return $data['access_token'];
}else{
return "Error occurred while geting the access_token";
}
}
//Though URL request is https',cannot use file_get_contents.Using CURL while asking the JSON data
function http_request_json($url){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
$return = "<xml>
<ToUserName><![CDATA['.$toUser.']]</ToUserName>
<FromUserName><![CDATA['.$fromUser.']]</FromUserName>
<CreateTime>'.time.'</CreateTime>
<MsgType><![CDATA[text]]></MsgType>
<Content><![CDATA['.text.']]</Content>
<FuncFlag>0</FuncFlag>
</xml>";
echo $return;
{
"button":[
{
"type":"click",
"name":"Daily Song",
"key":"V1001_TODAY_MUSIC"
},
{
"type":"click",
"name":" Artist Profile",
"key":"V1001_TODAY_SINGER"
},
{
"name":"Menu",
"sub_button":[
{
"type":"view",
"name":"Search",
"url":"http://www.soso.com/"
},
{
"type":"view",
"name":"Video",
"url":"http://v.qq.com/"
},
{
"type":"click",
"name":"Like us",
"key":"V1001_GOOD"
}]
}]
}
}
}
else
{
die('Access Denied');
}`enter code here`
?>

Related

Accessing object returned from GraphQL using curl

I have returned data using GraphQL / curl that looks like this:
{
"data" : {
"publisher" : {
"contracts" : {
"totalCount" : 11,
"count" : 1,
"resultList" : [
I want to get the resultList array and keep getting an error 'Warning: Attempt to read property "data" on string' when trying to do $result->data to move into the first object. What am I doing wrong?
My variable from the curl request is $result.
Update: I HAVE TRIED DECODING AND THE RETURNED DATA IS OF TYPE INT? How?
function getData($data_String){
$endpoint = "https://programs.api.cj.com/query";
$authToken = "pass";
$qry = '{"query":"{ publisher { contracts(publisherId: \"xxxxxxx\", limit: 1, filters: {advertiserId: \"'.$advertiser_id.'\"}) { totalCount count resultList { startTime endTime status advertiserId programTerms { id name specialTerms { name body } isDefault actionTerms { id actionTracker { id name description type } lockingMethod { type durationInDays } performanceIncentives { threshold { type value } reward { type commissionType value } currency } commissions { rank situation { id name } itemList { id name } promotionalProperties { id name } rate { type value currency } } } } } } } }","variables":null}';
$headers = array();
$headers[] = 'Content-Type: application/json';
$headers[] = 'Authorization: Bearer '.$authToken;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $endpoint);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 0);
curl_setopt($ch, CURLOPT_POSTFIELDS, $qry);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$result = curl_exec($ch);
if (curl_errno($ch)) {
echo 'Error:' . curl_error($ch);
}
curl_close($ch);
$data = json_decode($result);
return $data;
}
First, be sure to check if the result is a valid json.
Then use json_decode to get an object
$result = json_decode($result);
if (is_object($result)) {
if (!empty($result->data->publisher->contracts->resultList)) {
$resultList = $result->data->publisher->contracts->resultList;
}
} else {
// Log or something
error_log("json decode return: " . print_r($result, true))
}

Clear session after checkout with custom payment method

Im using custom payment method for payments with credit and debit cards in OpenCart 2.1.0.1 but I am facing a problem. When I make a successful purchase and I redirected to succsess.tpl page, after that when i continue shopping (in the same browser session) and make a second successful purchase - its not recording as new order with new order id! I will attach my controller, which can be the code for clearing session?
class ControllerPaymentFibank extends Controller {
public function index() {
$this->load->model('checkout/order');
$this->language->load('payment/fibank');
$data['button_confirm'] = $this->language->get('button_confirm');
if (!$this->config->get('fibank_test')) {
$communication_url = "https://mdpay.fibank.bg:9443/ecomm/MerchantHandler";
$payment_url = "https://mdpay.fibank.bg/ecomm/ClientHandler";
} else {
$communication_url = "https://mdpay-test.fibank.bg:9443/ecomm/MerchantHandler";
$payment_url = "https://mdpay-test.fibank.bg/ecomm/ClientHandler";
}
$order_info = $this->model_checkout_order->getOrder($this->session->data['order_id']);
if ($order_info) {
$data['action'] = $this->session->data['order_id'];
if (file_exists(DIR_TEMPLATE . $this->config->get('config_template') . '/template/payment/fibank.tpl')) {
return $this->load->view($this->config->get('config_template') . '/template/payment/fibank.tpl', $data);
} else {
return $this->load->view('default/template/payment/fibank.tpl', $data);
}
}
}
public function make_payment() {
$this->load->model('checkout/order');
$this->language->load('payment/fibank');
$data['button_confirm'] = $this->language->get('button_confirm');
if (!$this->config->get('fibank_test')) {
$communication_url = "https://mdpay.fibank.bg:9443/ecomm/MerchantHandler";
$payment_url = "https://mdpay.fibank.bg/ecomm/ClientHandler";
} else {
$communication_url = "https://mdpay-test.fibank.bg:9443/ecomm/MerchantHandler";
$payment_url = "https://mdpay-test.fibank.bg/ecomm/ClientHandler";
}
$order_info = $this->model_checkout_order->getOrder($this->session->data['order_id']);
if ($order_info) {
$ip = $this->get_client_ip();
$amount = $this->currency->format($order_info['total'], 'BGN', '', false);
$amount *= 100;
$post_request="command=v&amount=".$amount."&currency=975&client_ip_addr=".$ip."&description=".$this->session->data['order_id']."&msg_type=SMS";
$res = $this->execute_fibank_query($communication_url, $post_request);
$result = str_replace("TRANSACTION_ID: ", "", $res);
$this->model_checkout_order->addOrderHistory($this->session->data['order_id'], '1', $result);
$_SESSION['order_id']=$this->session->data['order_id'];
header("location:".$payment_url."?trans_id=".rawurlencode($result));
}
exit();
}
public function callback() {
if (isset($this->request->post['trans_id'])) {
$tranz_id = $this->request->post['trans_id'];
} else {
$tranz_id = '';
}
if (!$this->config->get('fibank_test')) {
$communication_url = "https://mdpay.fibank.bg:9443/ecomm/MerchantHandler";
$payment_url = "https://mdpay.fibank.bg/ecomm/ClientHandler";
} else {
$communication_url = "https://mdpay-test.fibank.bg:9443/ecomm/MerchantHandler";
$payment_url = "https://mdpay-test.fibank.bg/ecomm/ClientHandler";
}
if ($tranz_id!="" && $_SESSION['order_id']>0) {
$ip = $this->get_client_ip();
$request="command=c&trans_id=".rawurlencode($tranz_id)."&client_ip_addr=".$ip;
$result = $this->execute_fibank_query($communication_url, $request);
$res = explode("\n", $result);
$fibank_info = str_replace("RESULT: ", "", $res[0]);
$this->load->model('checkout/order');
$order_info = $this->model_checkout_order->getOrder($_SESSION['order_id']);
if ($fibank_info=="OK") {
$order_status = $this->config->get('fibank_order_status_id');
$this->model_checkout_order->addOrderHistory($_SESSION['order_id'], $order_status, $result);
$this->cart->clear();
header("location:/successfull-transaction");
}
else{
$order_status = $this->config->get('fibank_order_status_denied_id');
$this->model_checkout_order->addOrderHistory($_SESSION['order_id'], $order_status, $result);
$this->cart->clear();
header("location:/transaction-error");
}
}
}
function execute_fibank_query($url, $request){
// debug
$fp = fopen(dirname(__FILE__).'/errorlog.txt', 'w');
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_VERBOSE, 1);
// debug
curl_setopt($ch, CURLOPT_STDERR, $fp);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_FAILONERROR, 1);
curl_setopt($ch, CURLOPT_SSLCERT, $this->config->get('fibank_certificate_path'));
curl_setopt($ch, CURLOPT_SSLCERTTYPE, 'PEM');
curl_setopt($ch, CURLOPT_SSLCERTPASSWD, $this->config->get('fibank_certificate_pass'));
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $request);
$result = curl_exec($ch);
return $result;
}
function get_client_ip(){
if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
$ip = $_SERVER['HTTP_CLIENT_IP'];
}
elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
$ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
}
else {
$ip = $_SERVER['REMOTE_ADDR'];
}
return $ip;
}
If you look at the file catalog/controller/checkout/success.php you will see the standard process that follows a successful order. If you've modified this at all, it's possible OpenCart isn't unsetting the session data. In that file, the controller checks if there is data set in the session:
if (isset($this->session->data['order_id'])) {
If it's true, the cart will be cleared with this line:
$this->cart->clear();
And, following the UserActivity logging, the session data is unset with this code:
unset($this->session->data['shipping_method']);
unset($this->session->data['shipping_methods']);
unset($this->session->data['payment_method']);
unset($this->session->data['payment_methods']);
unset($this->session->data['guest']);
unset($this->session->data['comment']);
unset($this->session->data['order_id']);
unset($this->session->data['coupon']);
unset($this->session->data['reward']);
unset($this->session->data['voucher']);
unset($this->session->data['vouchers']);
unset($this->session->data['totals']);

How to improve code structure in PHP?

I've created two method in my controller in Laravel to fetch data from another website using PHP CURL and pass to view.
I will used httpData method for initial ID and URL and getHttpCode method to get HTTP_code to find any errors will happen when I fetch data from another website But I don't much understand about this below code performance and how can I testing In PHPstrom to make sure with performance
Here is my function
private function httpData($url =null, $id = null)
{
if($id){
$url = 'http://assignment.gae.golgek.mobi/api/v1/items/'.$id;
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLINFO_PRETRANSFER_TIME, 30);
curl_setopt($ch, CURLINFO_HTTP_CODE, true);
curl_setopt($ch, CURLOPT_PRIVATE, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
if (!$executed = curl_exec($ch)) {
$res = $executed;
$data = false;
curl_close($ch);
} else {
if ($this->http_code = $this->getHttpCode(curl_getinfo($ch))) {
$res = $this->http_code;
$data = $executed;
} else {
$res = false;
}
}
return ['s_respond' => $res, 'data' => $executed];
}
private function getHttpCode($http)
{
if (is_array($http)) {
if (!empty($http['http_code'] || $http['http_code'] != 0)) {
return $http['http_code'];
} else {
return false;
}
} else {
return false;
}
}
And I will call this method as below
public function sendData()
{
$url = 'website/api/v1/products';
$data = $this->httpData($url);
return view('products.list', ['data'=>$data]);
}
Thanks for help
I suggest you to addopt the 'early return pattern'.
I did a rewrite in you getHttpCode, it seems more clear to me:
private function getHttpCode($http)
{
if ( !is_array($http)
|| empty($http['http_code'])
|| $http['http_code'] === 0)
{
return false;
}
return $http['http_code'];
}

Telegram Bot sending a message without needing a ,message to trigger it

I am trying to let a Telegram bot send a message to a group without the need of a message by a user to trigger it. To be more specific i am trying to set up a birthday reminder where the bot querys a database, compares entries to the current date and broadcaststs a "Happy birthday" message in the group. As said i would like to do it via a cronjob that opens up the PHP script everyday and lets the bot broadcast it.
My problem is I checked all of Telegrams documentations and demo codes (https://core.telegram.org/bots/samples) but all of it are based on a User triggering the bot by sending a message.
My question is, if anyone was already able to implement a similar functionality and could aid me in extending my code? What might be worth mentioning is that the Bot is already integrated into the Group Chat and i have the chat id that would be needed for the bot to target the chat.
My code is as follows (i have to admit i copied it over from the demo examples):
<?php
define('BOT_TOKEN', 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX');
define('API_URL', 'https://api.telegram.org/bot'.BOT_TOKEN.'/');
function apiRequestWebhook($method, $parameters) {
if (!is_string($method)) {
error_log("Method name must be a string\n");
return false;
}
if (!$parameters) {
$parameters = array();
} else if (!is_array($parameters)) {
error_log("Parameters must be an array\n");
return false;
}
$parameters["method"] = $method;
header("Content-Type: application/json");
echo json_encode($parameters);
return true;
}
function exec_curl_request($handle) {
$response = curl_exec($handle);
if ($response === false) {
$errno = curl_errno($handle);
$error = curl_error($handle);
error_log("Curl returned error $errno: $error\n");
curl_close($handle);
return false;
}
$http_code = intval(curl_getinfo($handle, CURLINFO_HTTP_CODE));
curl_close($handle);
if ($http_code >= 500) {
// do not wat to DDOS server if something goes wrong
sleep(10);
return false;
} else if ($http_code != 200) {
$response = json_decode($response, true);
error_log("Request has failed with error {$response['error_code']}: {$response['description']}\n");
if ($http_code == 401) {
throw new Exception('Invalid access token provided');
}
return false;
} else {
$response = json_decode($response, true);
if (isset($response['description'])) {
error_log("Request was successfull: {$response['description']}\n");
}
$response = $response['result'];
}
return $response;
}
function apiRequest($method, $parameters) {
if (!is_string($method)) {
error_log("Method name must be a string\n");
return false;
}
if (!$parameters) {
$parameters = array();
} else if (!is_array($parameters)) {
error_log("Parameters must be an array\n");
return false;
}
foreach ($parameters as $key => &$val) {
// encoding to JSON array parameters, for example reply_markup
if (!is_numeric($val) && !is_string($val)) {
$val = json_encode($val);
}
}
$url = API_URL.$method.'?'.http_build_query($parameters);
$handle = curl_init($url);
curl_setopt($handle, CURLOPT_RETURNTRANSFER, true);
curl_setopt($handle, CURLOPT_CONNECTTIMEOUT, 5);
curl_setopt($handle, CURLOPT_TIMEOUT, 60);
return exec_curl_request($handle);
}
function apiRequestJson($method, $parameters) {
if (!is_string($method)) {
error_log("Method name must be a string\n");
return false;
}
if (!$parameters) {
$parameters = array();
} else if (!is_array($parameters)) {
error_log("Parameters must be an array\n");
return false;
}
$parameters["method"] = $method;
$handle = curl_init(API_URL);
curl_setopt($handle, CURLOPT_RETURNTRANSFER, true);
curl_setopt($handle, CURLOPT_CONNECTTIMEOUT, 5);
curl_setopt($handle, CURLOPT_TIMEOUT, 60);
curl_setopt($handle, CURLOPT_POSTFIELDS, json_encode($parameters));
curl_setopt($handle, CURLOPT_HTTPHEADER, array("Content-Type: application/json"));
return exec_curl_request($handle);
}
function processMessage($message) {
// process incoming message
$message_id = $message['message_id'];
$chat_id = $message['chat']['id'];
if (isset($message['text'])) {
apiRequest("sendChatAction", array('chat_id' => $chat_id, "action" => "typing"));
// incoming text message
$text = $message['text'];
//Command for intializing the backend code for the birthday check (just to check its functionality but would prefer the code to run without a command)
if (strpos($text, "/geburtstagscheck") === 0) {
include 'skripte/start.php';
}
}}
define('WEBHOOK_URL', 'XXXXXXXXXXXXXX');
if (php_sapi_name() == 'cli') {
// if run from console, set or delete webhook
apiRequest('setWebhook', array('url' => isset($argv[1]) && $argv[1] == 'delete' ? '' : WEBHOOK_URL));
exit;
}
$content = file_get_contents("php://input");
$update = json_decode($content, true);
if (!$update) {
// receive wrong update, must not happen
exit;
}
if (isset($update["message"])) {
processMessage($update["message"]);
} ?>

reverse geocoding not working, Google Maps API v2

I'm using google maps api v2 and I am sending coordinates to my program. The localisation on the map works fine but I never get the adress...
Here is my class:
class reverseGeoCoding {
//put your code here
private $result;
private $latitude=null;
private $longitude=null;
private $adresse=null;
private $config;
public $contents;
function xml2ary(&$string) {
$parser = xml_parser_create();
xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
xml_parse_into_struct($parser, $string, $vals, $index);
xml_parser_free($parser);
$mnary=array();
$ary=&$mnary;
foreach ($vals as $r) {
$t=$r['tag'];
if ($r['type']=='open') {
if (isset($ary[$t])) {
if (isset($ary[$t][0])) $ary[$t][]=array(); else $ary[$t]=array($ary[$t], array());
$cv=&$ary[$t][count($ary[$t])-1];
} else $cv=&$ary[$t];
if (isset($r['attributes'])) {
foreach ($r['attributes'] as $k=>$v) $cv['_a'][$k]=$v;
}
$cv['_c']=array();
$cv['_c']['_p']=&$ary;
$ary=&$cv['_c'];
} elseif ($r['type']=='complete') {
if (isset($ary[$t])) { // same as open
if (isset($ary[$t][0])) $ary[$t][]=array(); else $ary[$t]=array($ary[$t], array());
$cv=&$ary[$t][count($ary[$t])-1];
} else $cv=&$ary[$t];
if (isset($r['attributes'])) {
foreach ($r['attributes'] as $k=>$v) $cv['_a'][$k]=$v;
}
$cv['_v']=(isset($r['value']) ? $r['value'] : '');
} elseif ($r['type']=='close') {
$ary=&$ary['_p'];
}
}
$this->del_p($mnary);
return $mnary;
}
// _Internal: Remove recursion in result array
function del_p(&$ary) {
foreach ($ary as $k=>$v) {
if ($k==='_p') unset($ary[$k]);
elseif (is_array($ary[$k])) $this->del_p($ary[$k]);
}
}
// Array to XML
function ary2xml($cary, $d=0, $forcetag='') {
$res=array();
foreach ($cary as $tag=>$r) {
if (isset($r[0])) {
$res[]=ary2xml($r, $d, $tag);
} else {
if ($forcetag) $tag=$forcetag;
$sp=str_repeat("\t", $d);
$res[]="$sp<$tag";
if (isset($r['_a'])) {
foreach ($r['_a'] as $at=>$av) $res[]=" $at=\"$av\"";
}
$res[]=">".((isset($r['_c'])) ? "\n" : '');
if (isset($r['_c'])) $res[]=ary2xml($r['_c'], $d+1);
elseif (isset($r['_v'])) $res[]=((!is_numeric($r['_v'])&&$r['_v']) ? '<![CDATA[' : false).$r['_v'].((!is_numeric($r['_v'])&&$r['_v']) ? ']]>' : false);
$res[]=(isset($r['_c']) ? $sp : '')."</$tag>\n";
}
}
return implode('', $res);
}
function formatGmapXML($xml,$returnXML=false,$error=false) {
$tmp = array();
$tmp['request']= $xml['kml']['_c']['Response']['_c']['name']['_v'];
$tmp['status']= $xml['kml']['_c']['Response']['_c']['Status']['_c']['code']['_v'];
// check our Response code to ensure success
if($tmp['status']=='200') {
$tmp['addressFull'] = $xml['kml']['_c']['Response']['_c']['Placemark']['_c']['address']['_v'];
$tmp['accuracy'] = $xml['kml']['_c']['Response']['_c']['Placemark']['_c']['AddressDetails']['_a']['Accuracy'];
$tmp['country'] = $xml['kml']['_c']['Response']['_c']['Placemark']['_c']['AddressDetails']['_c']['Country']['_c']['CountryName']['_v'];
$tmp['state'] = $xml['kml']['_c']['Response']['_c']['Placemark']['_c']['AddressDetails']['_c']['Country']['_c']['AdministrativeArea']['_c']['AdministrativeAreaName']['_v'];
$tmp['suburb'] = $xml['kml']['_c']['Response']['_c']['Placemark']['_c']['AddressDetails']['_c']['Country']['_c']['AdministrativeArea']['_c']['Locality']['_c']['LocalityName']['_v'];
$tmp['address'] = $xml['kml']['_c']['Response']['_c']['Placemark']['_c']['AddressDetails']['_c']['Country']['_c']['AdministrativeArea']['_c']['Locality']['_c']['Thoroughfare']['_c']['ThoroughfareName']['_v'];
$tmp['postcode'] = $xml['kml']['_c']['Response']['_c']['Placemark']['_c']['AddressDetails']['_c']['Country']['_c']['AdministrativeArea']['_c']['Locality']['_c']['PostalCode']['_c']['PostalCodeNumber']['_v'];
$tmp['coordinates'] = $xml['kml']['_c']['Response']['_c']['Placemark']['_c']['Point']['_c']['coordinates']['_v'];
if($tmp['addressFull']==null) {
$tmp['addressFull'] = $xml['kml']['_c']['Response']['_c']['Placemark'][0]['_c']['address']['_v'];
$tmp['accuracy'] = $xml['kml']['_c']['Response']['_c']['Placemark'][0]['_c']['AddressDetails']['_a']['Accuracy'];
$tmp['country'] = $xml['kml']['_c']['Response']['_c']['Placemark'][0]['_c']['AddressDetails']['_c']['Country']['_c']['CountryName']['_v'];
$tmp['state'] = $xml['kml']['_c']['Response']['_c']['Placemark'][0]['_c']['AddressDetails']['_c']['Country']['_c']['AdministrativeArea']['_c']['AdministrativeAreaName']['_v'];
$tmp['suburb'] = $xml['kml']['_c']['Response']['_c']['Placemark'][0]['_c']['AddressDetails']['_c']['Country']['_c']['AdministrativeArea']['_c']['Locality']['_c']['LocalityName']['_v'];
$tmp['address'] = $xml['kml']['_c']['Response']['_c']['Placemark'][0]['_c']['AddressDetails']['_c']['Country']['_c']['AdministrativeArea']['_c']['Locality']['_c']['Thoroughfare']['_c']['ThoroughfareName']['_v'];
$tmp['postcode'] = $xml['kml']['_c']['Response']['_c']['Placemark'][0]['_c']['AddressDetails']['_c']['Country']['_c']['AdministrativeArea']['_c']['Locality']['_c']['PostalCode']['_c']['PostalCodeNumber']['_v'];
$tmp['coordinates'] = $xml['kml']['_c']['Response']['_c']['Placemark'][0]['_c']['Point']['_c']['coordinates']['_v'];
}
$latlng = explode(',',$tmp['coordinates']);
$tmp['latitude'] = $latlng[1];
$tmp['longitude'] = $latlng[0];
}
// optional outputs
if($error) $tmp['error'] = $error;
if($returnXML) $tmp['xml'] = ary2xml($xml);
return $tmp;
}
/*
$q=$_GET['q'];
$latitude=$_GET['latitude'];
$longitude=$_GET['longitude'];
*/
function reverseGeoCoding() {
$this->config=new configInt();
}
function setLongitude($longitude) {
$this->longitude=$longitude;
}
function setLatitude($latitude) {
$this->latitude=$latitude;
}
function setadresse($adresse) {
$this->adresse=$adresse;
}
function getLongitude() {
return $this->longitude;
}
function getLatitude() {
return $this->latitude;
}
function getadresse() {
return $this->adresse;
}
function exec() {
if($this->longitude && $this->latitude ) {
$ch = curl_init("http://maps.google.com/maps/geo?output=xml&ll={$this->latitude},{$this->longitude}&key={$this->config->clefGoogle}");
}else {
$adresse=rawurlencode($this->adresse);
$ch = curl_init("http://maps.google.com/maps/geo?output=xml&q={$adresse}&key={$this->config->clefGoogle}");
}
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_AUTOREFERER, true);
curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 5.1; pl; rv:1.9) Gecko/2008052906 Firefox/3.0");
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_HTTPGET, true);
//curl_setopt($ch, CURLOPT_COOKIEJAR, "cookie.txt");
curl_setopt($ch, CURLOPT_VERBOSE, false);
$this->contents=curl_exec($ch);
$this->contents=$this->xml2ary($this->contents);
$this->result=$this->formatGmapXML($this->contents,false);
curl_close($ch);
if($this->longitude && $this->latitude ) {
$this->adresse=utf8_decode($this->result['addressFull']);
}else {
$this->latitude=$this->result['latitude'];
$this->longitude=$this->result['longitude'];
}
return $this->result;
}
}
?>
I'm using getAdress in my programm to save the adress in the database, but it never seems to work properly even though the coordinates are correct...
Try this:
$result = json_decode(file_get_contents('http://maps.googleapis.com/maps/api/geocode/json?latlng=40.714224,-73.961452&sensor=true'));
echo $result->results[0]->formatted_address;
function getaddress($lat, $lng) {
$url = 'http://maps.googleapis.com/maps/api/geocode/json?latlng=' . trim($lat) . ',' . trim($lng) . '&sensor=false';
$json = #file_get_contents($url);
$data = json_decode($json);
$status = $data->status;
if ($status == "OK")
return $data->results[0]->formatted_address;
else
return false;
}

Categories