So I have a custom Drupal module that outputs a formatted version of the song node's data based on a node id in the path (load/song/NID). This function works fine, and when I look at the url in my browser, I see that everything has loaded perfectly.
My module's code:
function load_song($nid){
$node = node_load($nid);
$songname = $node->title;
$albumid = $node->field_album['und'][0]['nid'];
$album = node_load($albumid);
$file = $album->field_cover['und'][0];
//Loads the album filepath from the file array returned above
$filepath = $file['uri'];
//The path returned is something like "public://file.jpg"
$filepath = str_replace("public://", "http://mysite.com/sites/default/files/styles/thumbnail/public/", $filepath);
//I then set a variable (imgurl) to the formatted filepath
$imgurl = $filepath;
$artistid = $album->field_artist['und'][0]['nid'];
$artist = node_load($artistid);
$artistname = $artist->title;
echo 'I output the variables + formatting here';
}
With the output, I then load it in my page.tpl.php file in Drupal using the jQuery .load function. My code:
function loadSongInfo(id) {
$("#current-song").html('Loading').load('http://mysite.com/load/song/' + id);
}
So with this input, what I get is the data from the url (which is perfectly formatted), and the other variables I load (artist name, song name, etc) working fine. However, where I have the filepath, all I get is an empty string.
This of course confuses the hell out of me, because it works fine in my browser, but when I call the function in jQuery, it loads all the other variables fine, except for the filepath.
I've tried (and got unsuccessful results):
Casting the variable $filepath to a string using three different methods
(I thought it might be something weird with the url) I replaced the filepath variable with just the static string of it ("http://mysite.com/sites/default/files/styles/thumbnail/public/file.jpg"), which returned the correct result, but still fails with the actual variable
var_dump
print_r
Does anyone have any idea why this isn't working?
Mymodule
function mymodule_menu(){
$items = array();
$items['js/song'] = array(
'page callback' => 'load_song',
'type' => MENU_CALLBACK,
'access arguments' => array('access content')
);
}
function load_song() {
$nid = $_POST['nid'];
$node = node_load($nid);
/*
* Check for node existing
* Return response.error if not loaded
*/
if(!$node->nid){
drupal_json(array('error' => t('Some text for error')));
die();
}
$songtitle = $node->title;
$albumid = $node->field_album['und'][0]['nid'];
$album = node_load($albumid);
$file = $album->field_cover['und'][0];
// Loads the album filepath from the file array returned above
$filepath = $file['uri'];
// The path returned is something like "public://file.jpg"
$filepath = str_replace("public://", "http://mysite.com/sites/default/files/styles/thumbnail/public/", $filepath);
// I then set a variable (imgurl) to the formatted filepath
$imagepath = $filepath;
$artistid = $album->field_artist['und'][0]['nid'];
$artist = node_load($artistid);
$artistname = $artist->title;
$object = array(
'song_title' => l($songtitle, 'node/'. $node->nid),
'image_path' => $imagepath,
'artist_name' => l($artistname, $artist->nid)
);
drupal_json(array('data' => $object));
die();
}
Javascript:
Drupal.behaviors.SongInit = function(context){
$("#current-song").html('Loading...').load("/load/song", {
nid : id
}, function(response, status, xhr) {
if (status == 'error') {
var msg = Drupal.t("Sorry but there was an error: ");
$("#current-song").html(msg + xhr.status + " " + xhr.statusText);
}
if (response.error) {
var msg = Drupal.t("Sorry but there was an error: ");
$("#current-song").html(msg);
}
else {
var msg = response.data.song_title + '<br />';
var msg = '<img src=/"' + response.data.image_path + ' /><br />';
var msg = response.data.artist_name + '<br />';
$("#current-song").html(msg);
Drupal.attachBehaviors(context);
}
});
}
Related
I'm trying to display an image but I am running into the error of Not allowed to load local resource: file:///C:/xampp/htdocs/public/images/profile/jimmy/status/boned.jpg in the browser console. What I am trying to do is use the base path provided by Zend Framework 2 but I'm retrieving the images in the model so (as far as I know), I can't use $this->basePath() like I would in the view.
This is my json string I am returning but would like to just be able to return /images/profile/jimmy/status/boned.jpg and whatever other images are in there.
I'm getting all the files outside of the directory 'status'. I am trying to get the files inside the status directory. When I did a var_dump this is what I get string(43) "C:\xampp\htdocs/public/images/profile/jimmy" I'm unclear why it is omitting the status directory after '/jimmy'
json string being returned:
{"feed":{"username":"Timmy","status":["this is jimmy, test"],"images":["videos","status","sithtoon.jpg","sith.jpg","edited_photos","diploma.jpg","current","albums","Screenshot_2016-08-09_21_28_13_361272.jpg","Screenshot_2016-08-05_17_55_48_500802.jpg","515gIIJ-Imgur.png",".htaccess"]}}
Here is the relevant PHP code (in the model):
public function listFriendsStatus()
{
$user_id = $this->getUserId()['id'];
// get the friend ids based on user id
// and then compare the friend id to the id in status table
$friend_query = new Select('friends');
$friend_query->columns(array('friend_id'))
->where(array('user_id' => $user_id));
$query = $this->sql->getAdapter()->query(
$this->sql->buildSqlString($friend_query),
Adapter::QUERY_MODE_EXECUTE
);
if ($query->count() > 0) {
$friend_id = array();
foreach ($query as $result) {
$friend_id[] = $result['friend_id'];
}
$status = new Select('status');
$status->columns(array('status'))
->where(array('id' => $friend_id));
$status_query = $this->sql->getAdapter()->query(
$this->sql->buildSqlString($status),
Adapter::QUERY_MODE_EXECUTE
);
if ($status_query->count() > 0) {
// check if a image was used
$members = new Select('members');
$members->columns(array('username'))
->where(array('id' => $friend_id));
$image_query = $this->sql->getAdapter()->query(
$this->sql->buildSqlString($members),
Adapter::QUERY_MODE_EXECUTE
);
if ($image_query->count() > 0) {
foreach ($image_query as $value) {
if (is_dir(getcwd() . '/images/profile/' . $value['username'] . '/status/')) {
$status_dir = pathinfo(getcwd() . '/images/profile/' . $value['username'] . '/status/');
}
}
$images = array();
chdir($status_dir['dirname']);
var_dump($status_dir['dirname']);
// retrieve the image inside the status directory
foreach (array_diff(scandir($status_dir['dirname'], 1), array('.', '..')) as $values) {
$images[] = $values;
}
} else {
throw new FeedException("The user does not exist in the user table.");
}
$status = array();
// get all the statuses
foreach ($status_query as $rows) {
$status[] = $rows['status'];
}
return array('username' => ucfirst($value['username']), 'status' => $status, 'images' => $images); // how to just get the basePath path with zf2
} else {
throw new FeedException("No status was found for your friends.");
}
} else {
throw new FeedException(sprintf("Could not locate any friends for %s", $this->user));
}
}
controller code:
public function getfriendstatusAction()
{
$layout = $this->layout();
$layout->setTerminal(true);
$view_model = new ViewModel();
$view_model->setTerminal(true);
try {
echo json_encode(array('feed' => $this->getStatusService()->listFriendsStatus()));
} catch (FeedException $e) {
echo json_encode(array('fail' => $e->getMessage()));
}
return $view_model;
}
jquery code:
$.getJSON('/members/feed/get-friend-status', function(data) {
$.each(data, function(i, item) {
$('.w3-container.w3-card-2.w3-white.w3-round.w3-margin').find('h4').html(data[i].username);
$('.w3-container.w3-card-2.w3-white.w3-round.w3-margin').find('p').html(data[i].status);
$('.w3-container.w3-card-2.w3-white.w3-round.w3-margin').find('img').attr('src', data[i].images);
});
}).fail(function(response) {
console.log(response);
});
I've been trying to use other directory functions provided with PHP but if I try anything, I run into the error directory could not be found. Basically what I am trying to do is use the similiar approach of $this->basePath() but in a model.
I hope that is clear enough..
Thanks!
Here is a screenshot of what I'm getting and how I want to get the status directory, not the directory outside of it.
I have an idea.
In your code is:
$status_dir = pathinfo(getcwd() . '/images/profile/' . $value['username'] . '/status/');
// ..............
chdir($status_dir['dirname']);
var_dump($status_dir['dirname']);
Try:
var_dump($status_dir);
I guess 'status' will be in 'basename' and / or in 'filename'
pathinfo gets last segment of argument string path as 'basename'.
Pathinfo only parses string as path and return array info, don't check it for isDir or isFile. Your correct chdir should looks like chdir($status_dir['dirname'] . '/' . $status_dir['basename'] ); if you need use of pathinfo.
In other words: dirname of 'images/profile/jimmy/status' is 'images/profile/jimmy' and its a reason why you don't see status in var_dump($status_dir['dirname']) and why chdir($status_dir['dirname']) not working correctly.
I want to copy json object to javascript array,
{
"profiledata1":{"id":0,"music":0,"image_x":130,"image_y":155,"mouth_x":0,"mouth_y":-28.125,"active":true,"default":false},
"profiledata2":{"id":1,"music":0,"image_x":130,"image_y":155,"mouth_x":0,"mouth_y":0,"active":true,"default":false},
"profiledata3":{"id":2,"music":0,"image_x":0,"image_y":0,"mouth_x":0,"mouth_y":0,"active":false,"default":false},
"profiledata4":{"id":3,"music":0,"image_x":0,"image_y":0,"mouth_x":0,"mouth_y":0,"active":false,"default":false},
"profiledata5":{"id":4,"music":0,"image_x":0,"image_y":0,"mouth_x":0,"mouth_y":0,"active":false,"default":false},
"upload":"http:\/\/localshost\/",
"format":"jpeg","status":1 }
This is my json object returned when i call some.php through ajax,
I want to copy profiledata1 to userdata_arr[0],profiledata2 to userdata_arr[1],profiledata3 to userdata_arr[2],profile4data to userdata_arr[3],profiledata5 to userdata_arr[5] in java script.
My java script is as follows,
$.ajax({
type: "POST",
url: "some.php",
data: {action:'load',
id:7}
}).done(function(o) {
var data = $.parseJSON(o);
if (!data || data === null) {
someError(true);
}else{
if(data.status==true){
userdata_arr[0] = data.profiledata1[0];
userdata_arr[1] = data.profiledata2[0];
userdata_arr[2] = data.profiledata3[0];
userdata_arr[3] = data.profiledata4[0];
userdata_arr[4] = data.profiledata5[0];
uploadDir = data.upload;
imgFormat = data.format;
somefunction();
}else{
someError(true);
}
}
});
when i execute this script i'm getting userdata_arr as undefined! Please help me to rectify this problem.
I'm also attaching the some.php here,
<?php
if ($_POST['action']=='load') {
$uid=$_POST['id'];
header("content-type:application/json");
// fetch contents from db with $uid;
$query = mysqli_query($link,$sql);
while ($row = mysqli_fetch_array($query)) {
$prof1 = $row['prof1'];
$prof2 = $row['prof2'];
$prof3 = $row['prof3'];
$prof4 = $row['prof4'];
$prof5 = $row['prof5'];
}
$jp1 = json_decode($prof1, 1);
$jp2 = json_decode($prof2, 1);
$jp3 = json_decode($prof3, 1);
$jp4 = json_decode($prof4, 1);
$jp5 = json_decode($prof5, 1);
echo json_encode($dta = array('profile1data' =>json_decode($prof1),'profile2data' =>json_decode($prof2),'profile3data' =>json_decode($prof3),'profile4data' =>json_decode($prof4),'profile5data' =>json_decode($prof5) ,'upload' =>'http://localhost/img/', 'format' =>'jpeg', 'status' =>1 )); ?>
Thanks in advance!
That's because you haven't declared your userdata_arr. To fix it, declare your array/object variable before using it. In your else code-block, do this:
else{
var userdata_arr = {}// declare your object
if(data.status==true){ //proceed to use your already-declared object, also notice the quote marks surrounding the object members/indexes
userdata_arr["0"] = data.profiledata1[0];
userdata_arr["1"] = data.profiledata2[0];
userdata_arr["2"] = data.profiledata3[0];
userdata_arr["3"] = data.profiledata4[0];
userdata_arr["4"] = data.profiledata5[0];
uploadDir = data.upload;
imgFormat = data.format;
somefunction();
}else{
someError(true);
}
}
From UI I make call:
$http.post('services/loadCategory.php', {
'id' :'1',
'type' :'string'
}).then(function(response) {
debugger;
...
}, function(response) {
...
});
On PHP service I can't get variables from body POST request:
include ("bd.php");
header("Content-type: text/html; charset=windows-1251");
// ----- ----- ----- ----- -----
if (isset($_POST['type'])) {
$type = $_POST['type'];
}
if (isset($_POST['id'])) {
$id = $_POST['id'];
}
//
exit(json_encode(
array('type' => iconv('windows-1251', 'UTF-8', $_POST['type']),
'id' => iconv('windows-1251', 'UTF-8', $_POST['id'])
)));
Request from service: { id:'', type:'' } How fix that?
When posting JSON to PHP, the $_POST variable is empty. To get the raw JSON in your PHP, use the following:
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
$data = json_decode(file_get_contents('php://input'), true);
}
You can then access the data with $data['id'] and $data['type']
Check the incoming $data with print_r($data);
After doing a quick search about this issue, it appears that PHP has a hard time deserializing the POST body sent by AngularJS. AngularJS sends all information JSON encoded (application/json) as compared to most other JavaScript variants which send the content as application/x-www-form-urlencoded.
To fix this, you should either set the content-type of your request to application/x-www-form-urlencoded or you can try one of the solutions below which came from a similar question.
Based on this question, it would seem that the following code (provided by Felipe Miosso) seems to solve the problem:
// Your app's root module...
angular.module('MyModule', [], function($httpProvider) {
// Use x-www-form-urlencoded Content-Type
$httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8';
/**
* The workhorse; converts an object to x-www-form-urlencoded serialization.
* #param {Object} obj
* #return {String}
*/
var param = function(obj) {
var query = '', name, value, fullSubName, subName, subValue, innerObj, i;
for(name in obj) {
value = obj[name];
if(value instanceof Array) {
for(i=0; i<value.length; ++i) {
subValue = value[i];
fullSubName = name + '[' + i + ']';
innerObj = {};
innerObj[fullSubName] = subValue;
query += param(innerObj) + '&';
}
}
else if(value instanceof Object) {
for(subName in value) {
subValue = value[subName];
fullSubName = name + '[' + subName + ']';
innerObj = {};
innerObj[fullSubName] = subValue;
query += param(innerObj) + '&';
}
}
else if(value !== undefined && value !== null)
query += encodeURIComponent(name) + '=' + encodeURIComponent(value) + '&';
}
return query.length ? query.substr(0, query.length - 1) : query;
};
// Override $http service's default transformRequest
$httpProvider.defaults.transformRequest = [function(data) {
return angular.isObject(data) && String(data) !== '[object File]' ? param(data) : data;
}];
});
Alternatively, you might be able to fix this problem by adding the following line of code to your PHP:
$params = json_decode(file_get_contents('php://input'),true);
I have the following code for displaying the json response which is thrown by php file when I am displaying it on the console it gives me TypeError: invalid 'in' operand e
Json response:
[{"keyword":"free dental care","svol":27100},{"keyword":"low cost dental care","svol":2900}]
JQuery:
$('#specialty').change(function(){
var spevalue=$( "#specialty option:selected" ).text();
var dataString='specialty='+ spevalue;
$.ajax({
type:"post",
datatype : 'json',
url:"GetKeyWordBids.php",
data:"specialty="+ spevalue,
success: function(data) {
$.each(data, function( index, value ) {
console.log(value.keyword);
});
},
});
});
Response :
TypeError: invalid 'in' operand e
GetKeyWordBids.php
<?php
require_once dirname(__FILE__).'/googleads-php-lib-master/examples/AdWords/v201409/init.php';
/**
* Runs the example.
* #param AdWordsUser $user the user to run the example with
*/
$specialty=$_POST['specialty'];
$ret=array();
// Include the initialization file
require_once UTIL_PATH . '/MapUtils.php';
function GetKeywordIdeasExample(AdWordsUser $user) {
global $ret;
$ret=array();
// Get the service, which loads the required classes.
$targetingIdeaService =
$user->GetService('TargetingIdeaService', ADWORDS_VERSION);
// Create seed keyword.
$keyword =$_POST['specialty'];
// Create selector.
$selector = new TargetingIdeaSelector();
$selector->requestType = 'IDEAS';
$selector->ideaType = 'KEYWORD';
$selector->requestedAttributeTypes = array('KEYWORD_TEXT', 'SEARCH_VOLUME',
'CATEGORY_PRODUCTS_AND_SERVICES');
// Create language search parameter (optional).
// The ID can be found in the documentation:
// https://developers.google.com/adwords/api/docs/appendix/languagecodes
// Note: As of v201302, only a single language parameter is allowed.
$languageParameter = new LanguageSearchParameter();
$english = new Language();
$english->id = 1000;
$languageParameter->languages = array($english);
// Create related to query search parameter.
$relatedToQuerySearchParameter = new RelatedToQuerySearchParameter();
$relatedToQuerySearchParameter->queries = array($keyword);
$selector->searchParameters[] = $relatedToQuerySearchParameter;
$selector->searchParameters[] = $languageParameter;
// Set selector paging (required by this service).
$selector->paging = new Paging(0, AdWordsConstants::RECOMMENDED_PAGE_SIZE);
do {
// Make the get request.
$page = $targetingIdeaService->get($selector);
// Display results.
if (isset($page->entries)) {
foreach ($page->entries as $targetingIdea) {
$data = MapUtils::GetMap($targetingIdea->data);
$keyword = $data['KEYWORD_TEXT']->value;
$search_volume = isset($data['SEARCH_VOLUME']->value)
? $data['SEARCH_VOLUME']->value : 0;
$categoryIds =
implode(', ', $data['CATEGORY_PRODUCTS_AND_SERVICES']->value);
// printf("Keyword idea with text '%s', category IDs (%s) and average "
//. "monthly search volume '%s' was found.\n",
// $keyword, $categoryIds, $search_volume);
array_push($ret,array("keyword"=>$keyword,"svol"=>$search_volume));
//$temp=array();
//$ret = array_merge($ret, array("keyword"=>$keyword,"svol"=>$search_volume));
//array_push($ret,$temp);
//$json=json_encode($temp);
//array_push($ret,$json);
}
//print_r($ret);
echo json_encode($ret);
}
else {
print "No keywords ideas were found.\n";
}
// Advance the paging index.
$selector->paging->startIndex += AdWordsConstants::RECOMMENDED_PAGE_SIZE;
} while ($page->totalNumEntries > $selector->paging->startIndex);
}
try {
// Get AdWordsUser from credentials in "../auth.ini"
// relative to the AdWordsUser.php file's directory.
$user = new AdWordsUser();
// Log every SOAP XML request and response.
$user->LogAll();
//$user->SetClientCustomerId(3310773561);
// Run the example.
GetKeywordIdeasExample($user);
} catch (Exception $e) {
printf("An error has occurred: %s\n", $e->getMessage());
}
I have a internal site which uses php to look through my msql customer database. Find any customers which do not have lat and lng fields filled in. Grab the postcodes and geocode them posting the lat and lng back to my database and plot the customers on the map. This is done by a cron job once a day. This worked fine using v.2 of google api. Since march or april its stopped. Im guessing because of v.3.
Jist my jl_jobscoordinates.cron.php file searches through the database picking up all the postcodes for empty lat and lng fields. Then calls a function from my geocode.class.php called doGeocode which uses xml to put togther and find results and save the lat and lng. Inside the geocodeclass it refers to a m_url which is the googleapi url which is saved inside my config file. I have updated this url to the new v.3 url which is http://maps.googleapis.com/maps/api/geocode/xml?address=%s&sensor=false. My map is back up and running, just nothing will geocode.
I will paste the two files jl_jobscooedinates.cron.php and geocode.class.php. I have commented out the old xml in the geocode which used to work with the old url.
The results of my cron is that it is not getting coordinates. e.g. -- [3-2013] Google could not find this Postcode: [COO041] Test Company Name, Oxfordshire OX26 4SS
jl_jobcoordinates.cron.php
require_once("../includes/config.php");
require_once(_PATH_JMS."/classes/session.class.php");
require_once(_PATH_JMS."/classes/db.class.php");
require_once(_PATH_JMS."/classes/lib.class.php");
require_once(_PATH_JMS."/classes/security.class.php");
require_once(_PATH_JMS."/classes/emails.class.php");
require_once(_PATH_JMS."/classes/geocode.class.php");
require_once(_PATH_JMS."/services/actiontrail.ds.php");
require_once(_PATH_JMS."/services/jobsdue.ds.php");
//-----------------------------------------------------
// Main Object Instances - Initialize what we require
//-----------------------------------------------------
$DB = new DB();
$Security = new Security($DB->i_db_conn);
$Lib = new Lib();
$Session = new Session();
$ActionTrail = new ActionTrail($DB, $Session, $Security);
$JobsDue = new JobsDue($DB, $Session, $Security, $ActionTrail);
$Geocode = new Geocode($Session, $Security);
$Emails = new Emails($DB, $Session, $Security);
//-----------------------------------------------------
// Save as a valid system user
//-----------------------------------------------------
$Session->save('USR_AUTH',_CRON_USER_NAME);
$Session->save('USR_PASS',_CRON_USER_PASS);
$Session->save('USR_IS_EMPLOYED', '1');
$Session->save('CONS',$Session->get('USR_AUTH'));
//-----------------------------------------------------
// Postcodes to Ignore - we cannot geocode these
//-----------------------------------------------------
$m_ignore = array("IRL","IRELAND","IRE","ITA","USA","BEL","EGY","GER","FR","FRA","HOL","POL");
//-----------------------------------------------------
// Get Jobs Due for all consultants for this year and next
//-----------------------------------------------------
$mY = (int) date("Y");
//-----------------------------------------------------
// Find t-cards without lat & lng
//-----------------------------------------------------
$m_errors = array();
for ($y=$mY;$y<=$mY+1;$y++)
{
for ($i=1;$i<=12;$i++)
{
$mM = (int) $i;
//echo "<br> mM =".$mM ." i =".$i;
$mJobs = $JobsDue->getAllJobsDue('%',$mM,$y,'%',NULL,NULL,FALSE); /* DON'T GET MISSED JOBS AS WE WILL START FROM JAN */
//echo "<br>mJobs =".$mJobs;
foreach ($mJobs as $row)
{
$m_postcode = $Lib->lib_str_clean(trim($row->postcode)); //this loops through each of the records and gets the post codes. m_postcodes are the postcodes found
echo "<br>m_postcode =".$m_postcode;
if (($row->latlngexists == 1)||(in_array($m_postcode,$m_ignore))||(in_array($row->card_id,$m_ignore))||(strlen($m_postcode)<=0)) continue;
if ($Lib->lib_ispostcode($m_postcode)) {
$m_coordinates = $Geocode->doGeocode($m_postcode);
echo "<br>m_coords =".$m_coordinates;//nothing displayed
if ($m_coordinates != NULL) {
$DB->setGeoTCard($row->card_id,$m_coordinates['lat'],$m_coordinates['lng']);
} else {
$m_err_desc = sprintf("[%s-%s] Google could not find this Postcode",$mM,$y);
$m_error = array(
"err_desc" => $m_err_desc,
"err_code" => $row->client_code,
"err_comp" => $row->title,
"err_depo" => $row->description,
"err_post" => $m_postcode
);
$m_errors[] = $m_error;
$m_ignore[] = $row->card_id;
}
sleep(_GEOCODE_PAUSE);
} else {
$m_err_desc = sprintf("[%s-%s] Postcode is invalid please check",$mM,$y);
$m_error = array(
"err_desc" => $m_err_desc,
"err_code" => $row->client_code,
"err_comp" => $row->title,
"err_depo" => $row->description,
"err_post" => $m_postcode
);
$m_errors[] = $m_error;
$m_ignore[] = $row->card_id;
}
}
}
}
if (count($m_errors) > 0) {
$Emails->doGeocodeErrNotify($m_errors);
}
geocode.class.php
class Geocode {
private $m_session = NULL;
private $m_security = NULL;
private $m_session_user;
private $m_session_pass;
private $m_key = _GMAP_KEY;
private $m_url = _GMAP_URL;
private $m_res = Array();
public function __construct($p_session,$p_security)
{
$this->m_session = $p_session;
$this->m_security = $p_security;
$this->m_session_user = $this->m_session->get('USR_AUTH');
$this->m_session_pass = $this->m_session->get('USR_PASS');
if ($this->m_security->doLogin($this->m_session_user,$this->m_session_pass) <= 0)
{
return NULL;
die;
}
}
public function doGeocode($p_postcode)
{
try {
// //$xml = new SimpleXMLElement(sprintf($this->m_url,$p_postcode,$this->m_key),0,TRUE); //OLD FOR V.2
$xml = new SimpleXMLElement(sprintf($this->m_url,$p_postcode),0,TRUE);
} catch (Exception $e) {
echo sprintf('Caught exception: %s', $e->getMessage());
return NULL;
die;
}
$st = $xml->Response->Status->code;
if (strcmp($st, "200") == 0)
{
$co = $xml->Response->Placemark->Point->coordinates;
$cs = preg_split("/[\s]*[,][\s]*/", $co);
$this->m_res = Array(
"lng" => $cs[0],
"lat" => $cs[1],
"alt" => $cs[2]
);
return $this->m_res;
} else {
return NULL;
}
}
}
I would really appriciate if someone could help me please. Im guessing its something to do with the new url in my config file and the current xml not set properly for the sensor??
My geocode stuff is still working fine just like this don't forget to use your own personal API key!
/**
* Geocode postcode to get long/lat used when adding suppliers and sites
* #param - $postcode - string - Input post code to geocode
* #return - $lat,$long - array - array containing latitude coords
*/
function geocode($postcode) {
$postcode = urlencode(trim($postcode)); // post code to look up in this case status however can easily be retrieved from a database or a form post
//$request_url = "http://maps.googleapis.com/maps/api/geocode/xml?address=".$postcode."&sensor=false"; // the request URL you'll send to google to get back your XML feed
define("MAPS_HOST", "maps.google.co.uk");
define("KEY", "YOUR API KEY HERE");
$base_url = "http://" . MAPS_HOST . "/maps/geo?output=xml" . "&key=" . KEY;
$request_url = $base_url . "&q=" . $postcode;
$xml = simplexml_load_file($request_url);
$status = $xml->Response->Status->code;
if (strcmp($status, "200") == 0) {
// Successful geocode
$geocode_pending = false;
$coordinates = $xml->Response->Placemark->Point->coordinates;
$coordinatesSplit = explode(",", $coordinates);
// Format: Longitude, Latitude, Altitude
return array("lat"=>$coordinatesSplit[1],"long"=>$coordinatesSplit[0]);
} else {
return array("lat"=>0,"long"=>0);
}
}