reverse geocoding not working, Google Maps API v2 - php

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;
}

Related

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'];
}

I am trying to extract info from a remote page and parse it to html. What I have is not working

I want to get all the information (date, location, price, etc.) from a remote page and parse it to HTML. I tried this script below but nothing appears to be happening:
<?php
$path = 'https://www.airbnb.com/s/Fukuoka-Prefecture--Japan?checkin=10%2F26%2F2015&checkout=11%2F03%2F2015&guests=&ss_id=xyn63dgs&page=1';
$html = file_get_contents($path);
$dom = new DOMDocument;
$dom->loadHTML($html);
foreach ($dom->getElementsByTagName('div') as $tag) {
if ($tag->getAttribute('class') === 'col-sm-12 row-space-2 col-md-6') {
echo $tag->nodeValue;
}
}
If you look at the error returned from the file_get_contents() it's giving you an error:
HTTP request failed! HTTP/1.0 403 Forbidden in yada/yada/yada.php
Try using a cURL library (or script) that will emulate a browser, similar to below (this is what I use when file_get_contents() fails. If it fails, remember that cURL is basically stateless, so if the destination site uses something based on sessions or cookies, you might be S.O.L.):
<?php
class cURL
{
public $response;
protected $sendHeader;
protected $PostFields;
private $query;
public function __construct($query = '')
{
$this->sendHeader = false;
$this->query = $query;
if(!empty($this->query)) {
if(!is_array($this->query))
$this->response = $this->Connect($this->query);
else
$this->encode();
}
}
public function SendPost($array = array())
{
$this->PostFields['payload'] = $array;
$this->PostFields['query'] = http_build_query($array);
return $this;
}
public function Connect($_url,$deJSON = true)
{
// Remote Connect
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
if(strpos($_url,"https://") !== false) {
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,2);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST,2);
}
if(!empty($this->PostFields['payload'])) {
curl_setopt($ch, CURLOPT_POST, count($this->PostFields['payload']));
curl_setopt($ch, CURLOPT_POSTFIELDS, $this->PostFields['query']);
}
if(!empty($this->sendHeader))
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11) AppleWebKit/601.1.56 (KHTML, like Gecko) Version/9.0 Safari/601.1.56');
$decode = curl_exec($ch);
$_response = ($deJSON)? json_decode($decode, true) : $decode;
$error = curl_error($ch);
curl_close($ch);
return (empty($error))? $_response: $error;
}
public function emulateBrowser()
{
$this->sendHeader = true;
return $this;
}
public function encode($_filter = 0)
{
foreach($this->query as $key => $value) {
$string[] = urlencode($key).'='.urlencode($value);
}
if($_filter == true)
$string = array_filter($string);
return implode("&",$string);
}
}
To use:
$path = 'https://www.airbnb.com/s/Fukuoka-Prefecture--Japan?checkin=10%2F26%2F2015&checkout=11%2F03%2F2015&guests=&ss_id=xyn63dgs&page=1';
$cURL = new cURL();
$html = $cURL->emulateBrowser()->connect($path,false);
$dom = new DOMDocument;
$dom->loadHTML($html);
foreach ($dom->getElementsByTagName('div') as $tag) {
if ($tag->getAttribute('class') === 'col-sm-12 row-space-2 col-md-6') {
echo $tag->nodeValue;
}
}

Searching on JSON pages

I am searching products on an e-commerce website using their API. The API returns all the information in JSON format as a response. Each JSON response has 50 items and a URL that has 50 other items and so on. So to match the searched string with product titles, I need to parse all the JSON files sequentially. But if the item to be searched is on the last page, it is taking about 40 minutes to reach there. Can you please help on how I can reduce that time?
My website is currently hosted on localhost(XAMPP).
index.php
$fk = new Flipkart();
$fk->getProductFeedJason($fk->result);
for($i=0; $i<51; $i++)
{
if($fk->flag==1)
break;
$fk->curl($fk->links[$i]);
$fk->getProducts($fk->result, $sstring);
}
flipkart.php
<?php
class Flipkart
{
private $baseUrl = "https://affiliate-api.flipkart.net/affiliate/api/psblesson.json";
private $headers = array(
'Fk-Affiliate-Id: id',
'Fk-Affiliate-Token: token'
);
public $result;
public $links;
public $mainLinksCount=0;
public $pc=0;
public $id;
public $title;
public $image;
public $sellingPrice;
public $maximumRetailPrice;
public $productURL;
public $flag=0;
function __construct()
{
ini_set('max_execution_time', 0);
ini_set('memory_limit', '1024M');
$this->curl($this->baseUrl);
}
public function curl($url)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, $this->headers);
curl_setopt($ch, CURLOPT_TIMEOUT, 60);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$this->result = curl_exec($ch);
curl_close($ch);
}
public function getProductFeedJason($res)
{
$i=0;
$productFeeds = json_decode($res, TRUE);
$this->links = $productFeeds['apiGroups']['affiliate']['apiListings'];
foreach($this->links as $keys=>$value)
{
$this->links[$i] = $value['availableVariants']['v0.1.0']['get'];
//echo $this->links[$i];
$i = $i + 1;
}
}
public function getProducts($res, $str)
{
$products = null;
$products = json_decode($res, TRUE);
$outerPart = $products['productInfoList'];
$nextUrl = $products['nextUrl'];
//echo $nextUrl.'<br />';
foreach($outerPart as $data)
{
$t = $data['productBaseInfo']['productAttributes']['title'];
similar_text($str, $t, $percent);
if($percent>70)
{
$this->id[$this->pc] = $data['productBaseInfo']['productIdentifier'] ['productId'];
//echo $this->id[$this->pc].'<br />';
$this->title[$this->pc] = $data['productBaseInfo']['productAttributes']['title'];
//echo $this->title[$this->pc].'<br />';
$this->image[$this->pc] = $data['productBaseInfo']['productAttributes']['imageUrls']['400x400'];
//echo $this->image[$this->pc].'<br />';
$this->sellingPrice[$this->pc] = $data['productBaseInfo']['productAttributes']['sellingPrice']['amount'];
//echo $this->sellingPrice[$this->pc].'<br />';
$this->maximumRetailPrice[$this->pc] = $data['productBaseInfo']['productAttributes']['maximumRetailPrice']['amount'];
//echo $this->maximumRetailPrice[$this->pc].'<br />';
$this->productUrl[$this->pc] = $data['productBaseInfo']['productAttributes']['productUrl'];
//echo $this->productUrl[$this->pc].'<br />';
$this->pc = $this->pc+1;
if($this->pc >=10)
{
$this->flag=1;
break;
}
}
}
if($nextUrl && $this->flag==0)
{
$this->curl($nextUrl);
$this->getProducts($this->result, $str);
}
}
}
?>

Call Sharepoint WebService with PHP SoapClient

I extended the PHP SoapClient to use it with NTLM Sharepoint Authentication:
class NTLMSoapClient extends SoapClient {
function __doRequest($request, $location, $action, $version) {
$headers = array(
'Method: POST',
'Connection: Keep-Alive',
'User-Agent: PHP-SOAP-CURL',
'Content-Type: text/xml; charset=utf-8',
'SOAPAction: "' . $action . '"',
);
$this->__last_request_headers = $headers;
$ch = curl_init($location);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $request);
curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_NTLM);
curl_setopt($ch, CURLOPT_USERPWD, $this->user . ':' . $this->password);
$response = curl_exec($ch);
return $response;
}
function __getLastRequestHeaders() {
return implode("n", $this->__last_request_headers) . "n";
}
public final function __call($methodName, array $methodParams) {
/*
* Is soapClient set? This check may look double here but in later
* developments it might help to trace bugs better and it avoids calls
* on wrong classes if $soapClient got set to something not SoapClient.
*/
if (!$this->soapClient instanceof \SoapClient) {
// Is not set
throw new \Exception('Variable soapClient is not a SoapClient class, have: ' . gettype($this->soapClient), 0xFF);
}
// Is it a "SOAP callback"?
if (substr($methodName, 0, 2) == '__') {
// Is SoapClient's method
$returned = call_user_func_array(array($this->soapClient, $methodName), $methodParams);
} else {
// Call it
$returned = $this->soapClient->__call($methodName, $methodParams);
}
// Return any values
return $returned;
}
}
class SPNTLMSoapClient extends NTLMSoapClient {
protected $user = 'xxxxxx';
protected $password = 'xxxxxxx';
}
class NTLMStream {
private $path;
private $mode;
private $options;
private $opened_path;
private $buffer;
private $pos;
public function stream_open($path, $mode, $options, $opened_path) {
echo "[NTLMStream::stream_open] $path , mode=$mode n";
$this->path = $path;
$this->mode = $mode;
$this->options = $options;
$this->opened_path = $opened_path;
$this->createBuffer($path);
return true;
}
public function stream_close() {
echo "[NTLMStream::stream_close] n";
curl_close($this->ch);
}
public function stream_read($count) {
echo "[NTLMStream::stream_read] $count n";
if (strlen($this->buffer) == 0) {
return false;
}
$read = substr($this->buffer, $this->pos, $count);
$this->pos += $count;
return $read;
}
public function stream_write($data) {
echo "[NTLMStream::stream_write] n";
if (strlen($this->buffer) == 0) {
return false;
}
return true;
}
public function stream_eof() {
echo "[NTLMStream::stream_eof] ";
if ($this->pos > strlen($this->buffer)) {
echo "true n";
return true;
}
echo "false n";
return false;
}
/* return the position of the current read pointer */
public function stream_tell() {
echo "[NTLMStream::stream_tell] n";
return $this->pos;
}
public function stream_flush() {
echo "[NTLMStream::stream_flush] n";
$this->buffer = null;
$this->pos = null;
}
public function stream_stat() {
echo "[NTLMStream::stream_stat] n";
$this->createBuffer($this->path);
$stat = array(
'size' => strlen($this->buffer),
);
return $stat;
}
public function url_stat($path, $flags) {
echo "[NTLMStream::url_stat] n";
$this->createBuffer($path);
$stat = array(
'size' => strlen($this->buffer),
);
return $stat;
}
/* Create the buffer by requesting the url through cURL */
private function createBuffer($path) {
if ($this->buffer) {
return;
}
echo "[NTLMStream::createBuffer] create buffer from : $pathn";
$this->ch = curl_init($path);
curl_setopt($this->ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($this->ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
curl_setopt($this->ch, CURLOPT_HTTPAUTH, CURLAUTH_NTLM);
curl_setopt($this->ch, CURLOPT_USERPWD, $this->user . ':' . $this->password);
echo $this->buffer = curl_exec($this->ch);
echo "[NTLMStream::createBuffer] buffer size : " . strlen($this->buffer) . "bytesn";
$this->pos = 0;
}
}
class SPNTLMStream extends NTLMStream {
protected $user = 'xxxxxxx';
protected $password = 'xxxxxxxx';
}
stream_wrapper_unregister('https');
stream_wrapper_register('https', 'SPNTLMStream') or die("Failed to register protocol");
$wsdl = "https://wxxxxxxxxx?WSDL";
$client = new SPNTLMSoapClient($wsdl);
I succesfully call: "print_r($client->__getFunctions())" and get the following:
Array
(
[0] => CopyIntoItemsLocalResponse CopyIntoItemsLocal(CopyIntoItemsLocal $parameters)
[1] => CopyIntoItemsResponse CopyIntoItems(CopyIntoItems $parameters)
[2] => GetItemResponse GetItem(GetItem $parameters)
[3] => CopyIntoItemsLocalResponse CopyIntoItemsLocal(CopyIntoItemsLocal $parameters)
[4] => CopyIntoItemsResponse CopyIntoItems(CopyIntoItems $parameters)
[5] => GetItemResponse GetItem(GetItem $parameters)
)
My Question now is: How do I call these Methods with $client and parameters,
$client->__call('CopyIntoItems', $params) doesnt work
$client->CopyIntoItems($params) doesnt work
I never get any Response.....
Thx in advance....

How to develop user defined menu on wechat

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`
?>

Categories