I have a default currency as USD.
The part of the class below allow to convert different currencies but my problem is the conversion is always based in EUR as default.
How to update the function to use USD as default if it selected ?
Thank you
EUR = 1 (default)
USD = 1.10
This approach works very well for any currencies
EUR = 0.9
USD = 1 (default)
This approach do not work because USD is in default and the result is always like above.
Note :
$currenciesAdmin->getAll() take all the currencies with the code (EUR) and the title (Euro) for example.
The value of EUR is always null because the convertion is based on EUR as default (see link ecb.europa.eu for the values)
public function getConvertCurrency()
{
$currenciesAdmin = new CurrenciesAdmin();
$XML = HTTP::getResponse([
'url' => 'https://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml'
]);
if (empty($XML)) {
throw new \Exception('Can not load currency rates from the European Central Bank website');
}
$currencies = [];
foreach ($currenciesAdmin->getAll() as $c) {
$currencies[$c['id']] = null;
}
$XML = new \SimpleXMLElement($XML);
foreach ($XML->Cube->Cube->Cube as $rate) {
if (array_key_exists((string)$rate['currency'], $currencies)) {
$currencies[(string)$rate['currency']] = (float)$rate['rate'];
}
}
foreach ($currencies as $code => $value) {
if (!is_null($value)) {
try {
$this->db->save('currencies', [
'value' => $value,
'last_updated' => 'now()'
], [
'code' => $code
]);
} catch (\PDOException $e) {
trigger_error($e->getMessage());
}
}
}
}
Normally you'd use an API that allows you to select a base currency and do the conversion that way. That said, if you need to work with this dataset I believe the following approach may work for you:
$sourceCurrency = 'EUR'; // Your data source uses this as the base value
$defaultCurrency = 'USD'; // Read this from desired location
$currencies = [];
foreach ($currenciesAdmin->getAll() as $c) {
$currencies[$c['id']] = null;
}
// This is a constant
$currencies[$sourceCurrency] = 1;
$XML = new \SimpleXMLElement($XML);
foreach ($XML->Cube->Cube->Cube as $rate) {
$code = (string)$rate['currency'];
if (array_key_exists($code, $currencies)) {
$currencies[$code] = (float)$rate['rate'];
}
}
if ($defaultCurrency !== $sourceCurrency) {
// Conversion is required
$convertedCurrencies = [];
foreach (array_keys($currencies) as $code) {
$convertedCurrencies[$code] = $currencies[$code] / $currencies[$defaultCurrency];
}
$currencies = $convertedCurrencies;
}
// Use $currencies as normal with the adjusted values
Below is an interactive demo that contains the JavaScript equivalent code that you can test in your browser:
(() => {
const currencyDropdown = document.querySelector('select');
const selForm = document.querySelector('form');
const sourceCurrency = 'EUR';
let cachedData = null;
const generateTable = async(first) => {
const defaultCurrency = first ? sourceCurrency : currencyDropdown.options[currencyDropdown.selectedIndex].value;
if (cachedData === null)
cachedData = await fetch('https://cors-anywhere.herokuapp.com/https://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml').then(r => r.text()).then(str => (new window.DOMParser()).parseFromString(str, "text/xml"));
let currencies = Array.from(cachedData.querySelectorAll('Cube > Cube > Cube'))
.reduce((a, c) => ({ ...a,
[c.attributes.currency.value]: parseFloat(c.attributes.rate.value)
}), {});
currencies.EUR = 1;
const currencyKeys = Object.keys(currencies).sort();
currencyDropdown.innerHTML = currencyKeys.map(code => `<option${code === defaultCurrency ? ' selected' : ''}>${code}</option>`)
if (sourceCurrency !== defaultCurrency) {
const convertedCurrencies = currencyKeys.reduce((a, code) => ({
...a,
[code]: currencies[code] / currencies[defaultCurrency],
}), {});
currencies = convertedCurrencies;
}
let tbl = document.querySelector('table');
if (tbl !== null)
tbl.remove();
tbl = document.createElement('table');
tbl.innerHTML = '<tr><th>code</th><th>value</th></tr>' +
(currencyKeys.map(
code => `<tr><td>${code}</td><td>${currencies[code]} ${defaultCurrency}</td></tr>`).join(''));
document.body.appendChild(tbl);
selForm.hidden = false;
};
selForm.addEventListener('submit', (e) => {
e.preventDefault();
generateTable(false);
});
generateTable(true);
})();
<form hidden>
<label>
Default currency:
<select></select>
<input type="submit">
</label>
</form>
<table>
<tr>
<td>Loading…</td>
</tr>
</table>
Related
I want to fetch all products from Square Catalog.
Here is the code:
require 'vendor/autoload.php';
use Square\SquareClient;
use Square\LocationsApi;
use Square\Exceptions\ApiException;
use Square\Http\ApiResponse;
use Square\Models\ListLocationsResponse;
use Square\Environment;
$client = new SquareClient([
'accessToken' => '{{access_token}}',
'environment' => Environment::SANDBOX,
]);
//Providing SKU
$object_ids = ['GFLR20L', '232GGGD'];
$body = new \Square\Models\BatchRetrieveCatalogObjectsRequest($object_ids);
$body->setIncludeRelatedObjects(true);
$api_response = $client->getCatalogApi()->batchRetrieveCatalogObjects($body);
if ($api_response->isSuccess()) {
$result = $api_response->getResult();
} else {
$errors = $api_response->getErrors();
}
Output:
object(Square\Models\BatchRetrieveCatalogObjectsResponse)#13 (3)
{
["errors":"Square\Models\BatchRetrieveCatalogObjectsResponse":private] => NULL
["objects":"Square\Models\BatchRetrieveCatalogObjectsResponse":private] => NULL
["relatedObjects":"Square\Models\BatchRetrieveCatalogObjectsResponse":private] => NULL
}
**> Post Suggestions by sjosey:
My PHP Code:
Looking for Products with name Paper in it.**
$object_types = ['ITEM'];
$prefix_query = new \Square\Models\CatalogQueryPrefix('name', 'paper');
$query = new \Square\Models\CatalogQuery();
$query->setPrefixQuery($prefix_query);
> Storing Values Here
$body = new \Square\Models\SearchCatalogObjectsRequest();
$body->setObjectTypes($object_types);
$body->setQuery($query);
$body->setLimit(100);
$api_response = $client->getCatalogApi()->searchCatalogObjects($body);
> Fetching the api response here
if ($api_response->isSuccess()) {
$result = $api_response->getResult();
} else {
$errors = $api_response->getErrors();
}
> Echo Result
var_dump($result);
Here is the output:
object(Square\Models\SearchCatalogObjectsResponse)#15 (5) { ["errors":"Square\Models\SearchCatalogObjectsResponse":private]=> NULL ["cursor":"Square\Models\SearchCatalogObjectsResponse":private]=> NULL ["objects":"Square\Models\SearchCatalogObjectsResponse":private]=> NULL ["relatedObjects":"Square\Models\SearchCatalogObjectsResponse":private]=> NULL ["latestTime":"Square\Models\SearchCatalogObjectsResponse":private]=> string(20) "1776-07-04T00:00:00Z" }
object_ids are not the same as SKU; they are unique generated ids on Square's side. You would want to use the SearchCatalogObjects (POST /v2/catalog/search) endpoint instead to search by SKU. An example query using one of your SKUs would be:
{
"query": {
"exact_query": {
"attribute_name": "sku",
"attribute_value": "GFLR20L"
}
}
}
This will get your catalog object ids, but if you're interested in the inventory you would still need to use another endpoint to get the inventory, such as RetrieveInventoryCount (which takes the catalog_object_id's as the parameter).
Figured out the solution. The following codes fetches a list of all the products by Product IDS. The array can be used to set data as per requirements (By SKU or Anything)
require 'vendor/autoload.php';
use Square\SquareClient;
use Square\LocationsApi;
use Square\Exceptions\ApiException;
use Square\Http\ApiResponse;
use Square\Models\ListLocationsResponse;
use Square\Environment;
$client = new SquareClient([
'accessToken' => '{{access_token}}',
'environment' => Environment::PRODUCTION,
]);
$bag = [];
$cursor = null;
$ctr = 1;
$api_response = $client->getCatalogApi()->listCatalog($cursor, 'ITEM');
if ($api_response->isSuccess()) {
$result = $api_response->getResult();
} else {
$errors = $api_response->getErrors();
}
$g1 = $result;
$g2 = json_encode($g1);
$g3 = json_decode($g2);
$cursor = $g3->cursor;
$objects = $g3->objects;
$g4 = json_encode($objects);
$g5 = json_decode($g4);
foreach($g5 as $g51){
$bag[$g51->id] = $g51;
}
while($cursor != null){
$api_response2 = $client->getCatalogApi()->listCatalog($cursor, 'ITEM');
if ($api_response2->isSuccess()) {
$result2 = $api_response2->getResult();
} else {
$errors2 = $api_response2->getErrors();
}
$g6 = $result2;
$g7 = json_encode($g6);
$g8 = json_decode($g7);
$cursor = $g8->cursor;
$objects2 = $g8->objects;
$g9 = json_encode($objects2);
$g10 = json_decode($g9);
foreach($g10 as $g101){
$bag[$g101->id] = $g101;
}
}
var_dump(count($bag));
I have a list of financial launch. Each launch may or may not have multiple payments. So for every financial launch I look for a list of payments. I would like this list to be within its corresponding financial launch.
My complete function:
public function customerInvoice()
{
$_customer = filtra_int($this->input->post('cliente_id'));
$this->redireciona_id_nula($_customer, $this->url . '/ficha');
$_view = [];
$this->load->helper(['filter', 'string', 'currency', 'validate', 'phone']);
$_view['glyph'] = 'user';
$_view['enterprise'] = $this->enterprise;
$_view['buttons'] = $this->_getFormButtons($_customer, $this->url . '/ficha');
$this->load->model('lancamento_model', 'lancamentoModel');
$_view['releases'] = $this->lancamentoModel->getCustomerRelease($_customer);
foreach ($_view['releases'] as $i => $value) {
// $_view['releases']['order'][$i] = $this->lancamentoModel->getCustomerOrder($value->id);
$value['order'] = $this->lancamentoModel->getCustomerOrder($value->id);
}
$this->addBreadcrumb('Lançamentos', base_url() . 'lancamentos');
$this->addBreadcrumb('Ficha', base_url() . 'lancamentos/ficha');
$this->addBreadcrumb('Exibir');
$this->extras['css'][] = $this->load->view('lancamentos/consulta/ficha_cliente/form/css', null, true);
$this->extras['scripts'][] = $this->load->view('lancamentos/consulta/ficha_cliente/form/js', $_view, true);
// $pagina = $this->getHtmlPagina('Ficha cliente', $_view);
// $this->load->view('lancamentos/consulta/ficha_cliente/view/view', $pagina);
$this->output->set_content_type('application/json');
$this->output->set_output(json_encode($_view));
}
json result:
{
"release":{
"0":{
"id":"380",
"data_vcto":"2016-01-15",
"data_emissao":"2016-01-15",
"documento":"292\/1",
"vlr":"67.00",
"vlr_divida":"0.00"
},
"order":[
[
{
"id":"142206",
"data_vcto":"2016-01-15 09:59:24",
"vlr_desconto":"0.00",
"vlr_multa":"0.00",
"pago_em":"2018-11-19 09:59:24",
"conta_nome":"Caixa",
"tipo_nome":"Vendas",
"vlr_movimento":"67.00",
"tipo_pagamento_nome":"Dinheiro"
},
{
"id":"213",
"data_vcto":"2016-01-13 09:59:24",
"vlr_desconto":"0.00",
"vlr_multa":"0.00",
"pago_em":"2018-11-19 09:59:24",
"conta_nome":"Caixa",
"tipo_nome":"Vendas",
"vlr_movimento":"22.00",
"tipo_pagamento_nome":"Dinheiro"
}
]
]
}
}
I would like something like that
{
"release":{
"0":{
"id":"380",
"data_vcto":"2016-01-15",
"data_emissao":"2016-01-15",
"documento":"292\/1",
"vlr":"67.00",
"vlr_divida":"0.00",
"order":[
{
"id":"142206",
"data_vcto":"2016-01-15 09:59:24",
"vlr_desconto":"0.00",
"vlr_multa":"0.00",
"pago_em":"2018-11-19 09:59:24",
"conta_nome":"Caixa",
"tipo_nome":"Vendas",
"vlr_movimento":"67.00",
"tipo_pagamento_nome":"Dinheiro"
},
{
"id":"213",
"data_vcto":"2016-01-13 09:59:24",
"vlr_desconto":"0.00",
"vlr_multa":"0.00",
"pago_em":"2018-11-19 09:59:24",
"conta_nome":"Caixa",
"tipo_nome":"Vendas",
"vlr_movimento":"22.00",
"tipo_pagamento_nome":"Dinheiro"
}
]
}
}
}
it is possible ? And what do I have to do in the foreach?
Update: I did as #Yulio Aleman Jimenez suggested...but after that the error appeared
Fatal error: Cannot use object of type stdClass as array in C:\xampp\htdocs\beauty\application\controllers\Lancamentos.php on line 829
Message: Cannot use object of type stdClass as array
Error Print
I think you must change your code like this:
$_releases = $this->lancamentoModel->getCustomerRelease($_customer);
foreach ($_releases as $i => $value) {
// try with this changes
$value = $this->lancamentoModel->getCustomerOrder($value->id);
$_releases[$i] = (object)array_merge((array)$_releases[$i], array('order' => $value));
}
The thing is to store the array of orders in the order of each release.
Update
You have working with objects, it's the reazon you have to cast to array, add new values in order and then cast to object.
I'm posting value using color box from view to controller. First time it works perfectly fine but when I reopen the color box it POST the old value to the new.
This is my color box code:
$('#equipmentPopup').colorbox({
ajax: true,
width: "620px",
height: "450px",
href: showEquipment,
data: {
briefingId: $("#briefing_id").val(),
briefingDate: $("#Briefing_scheduled_date").val(),
briefingEndDate: $("#Briefing_scheduled_end_date").val(),
briefingEquipments: $('#BriefingEquipments').val()
}
});
This is my action code:
public function actionShowEquipment()
{
$this->layout = "//layouts/popup";
$equipmentConflicts = '';
$briefingId = $_POST['briefingId'];
$briefingDate = $_POST['briefingDate'];
$briefingEndDate = isset($_POST['briefingEndDate']) ? $_POST['briefingEndDate'] : '';
$serializeBriefingEquipments = isset($_POST['briefingEquipments']) ? $_POST['briefingEquipments'] : '';
$equipment = CHtml::listData(Equipment::model()->findAll(), 'id', 'name');
$briefingCenter = BriefingCenter::model()->findByPk(Yii::app()->user->currentBriefingCenterId);
if ($briefingId) {
$briefingEquipmentArr = BriefingEquipment::model()->findAll('briefing_id = :bId', array(':bId' => $briefingId));
if (!$briefingEquipmentArr) {
$briefingEquipmentArr[] = new BriefingEquipment();
}
} else if ($serializeBriefingEquipments) {
$serializeBriefingEquipments = unserialize($serializeBriefingEquipments);
}
$briefing = Briefing::model()->findByPk($briefingId);
if (!empty($briefing->scheduled_date) && !empty($briefing->scheduled_end_date)) {
$minDate = $briefing->scheduled_date;
$maxDate = $briefing->scheduled_end_date;
} else {
$minDate = $briefingDate;
$maxDate = $briefingEndDate;
}
echo $this->render('edit/equipment', array(
'briefing' => array(
'briefingId' => $briefingId,
'briefingDate' => $briefingDate,
'briefingEndDate' => $briefingEndDate,
),
'minDate' => strtotime($minDate),
'maxDate' => strtotime($maxDate),
'briefingEquipmentArr' => $briefingEquipmentArr,
'equipments' => $equipment,
'briefingCenter' => $briefingCenter,
'serializeBriefingEquipments' => $serializeBriefingEquipments,
'dateFormat' => Yii::app()->user->currentBriefingCenterDateFormat,
));
}
Your code does not work for me. I see there is no passed data by colorbox, so try changing data to this:
data: function() {
return {
briefingId: $("#briefing_id").val(),
briefingDate: $("#Briefing_scheduled_date").val(),
briefingEndDate: $("#Briefing_scheduled_end_date").val(),
briefingEquipments: $('#BriefingEquipments').val()
}
}
Maybe it will help.
I am trying to make a Map-Reduce command in PHP with exactly the same functions as in pure JavaScript and surprisingly the result is not the same. I have null values in PHP :-(
I have an "employees" collection, for each employee there is a list of "departments" to which he/she belongs.
So the Javascript map-reduce code (which works) to get the number of employees by department will be:
map = function() {
if (!this.department) {
return;
}
for (i in this.department) {
emit(this.department[i], 1);
};
};
reduce = function(key, values) {
var total = 0;
for (i in values) {
total += values[i];
};
return total;
};
retorno = db.runCommand({
"mapreduce": "employees",
"map": map,
"reduce": reduce,
"out": "employees_by_department"
});
if (retorno.ok != 1) {
print(retorno.errmsg);
};
resultado = db.employees_by_department.find();
while ( resultado.hasNext() ) {
printjson( resultado.next() );
}
And the equivalent PHP code (with null values) will be:
<?php
try {
$connection = new MongoClient( "mongodb://localhost" );
$db = $connection->selectDB("employees");
} catch (Exception $e) {
printf("Error: %s: %s\n", "Error al conectarse a MongoDB: ", $e->getMessage());
die();
}
$map = new MongoCode("function() {
if (!this.department) {
return;
}
for (i in this.department) {
emit(this.department[i], 1);
};
};");
$reduce = new MongoCode("reduce = function(key, values) {
var total = 0;
for (i in values) {
total += values[i];
};
return total;
};");
$retorno = $db->command(array(
"mapreduce" => "employees",
"map" => $map,
"reduce" => $reduce,
"out" => "employees_by_department_php"
));
if ($retorno["ok"] =! 1) {
print($retorno["errmsg"]);
}
else {
$resultado = $db->selectCollection("employees_by_department_php")->find();
foreach($resultado as $dep) {
printf("_id: \"%s\", value: %d\n", $dep["_id"], $dep["value"]);
}
}
?>
Any ideas?
UUpppss!! Solved! The problem was a typo error (a copy-paste problem) :-|
In PHP the first line of the reduce function, where it was
$reduce = new MongoCode("reduce = function(key, values) {
should be
$reduce = new MongoCode("function(key, values) {
I have a simple php function which get's the closest nearby city from a given latitude and longitude:
function findCity($lat, $lng, $username) {
$json_url = "http://api.geonames.org/findNearbyPlaceNameJSON?lat=" . $lat . "&lng=" . $lng . "&username=" . $username;
$json = file_get_contents($json_url);
$json = str_replace('},
]', "}
]", $json);
$data = json_decode($json);
echo "<pre>";
print_r($data);
echo "</pre>";
}
This method returns the following with lat: 51.992 and long: 4.89
stdClass Object
(
[geonames] => Array
(
[0] => stdClass Object
(
[countryName] => Netherlands
[adminCode1] => 11
[fclName] => city, village,...
[countryCode] => NL
[lng] => 4.876389
[fcodeName] => populated place
[distance] => 1.42349
[toponymName] => Langerak
[fcl] => P
[name] => Langerak
[fcode] => PPL
[geonameId] => 2751924
[lat] => 51.931667
[adminName1] => South Holland
[population] => 0
)
)
)
This returns the closest city, but I am looking for something like this. Where only the closest large city is returned. Is this possible? Or are there other alternatives to solve this. I've read about the Google Geocoding API, but we can't use it since we aren't using a Google map to show the results. (Note: the Geocoding API may only be used in conjunction with a Google map; geocoding results without displaying them on a map is prohibited. Source)
I know this isn't an actual programmer problem, but since the geonames forums are not really active, I figured I would post it here.
You need a list of the biggest cities. I didn't find an api call on geonames (maybe try freebase api for sorting by city relevance). Because the example list you show is short an static you could hard code it? If so you could use something shown below:
/*
* Haversine formula
* from: http://rosettacode.org/wiki/Haversine_formula#PHP
*/
class POI {
private $latitude;
private $longitude;
public function __construct($latitude, $longitude) {
$this->latitude = deg2rad($latitude);
$this->longitude = deg2rad($longitude);
}
public function getLatitude() {return $this->latitude;}
public function getLongitude(){return $this->longitude;}
public function getDistanceInMetersTo(POI $other) {
$radiusOfEarth = 6371000;// Earth's radius in meters.
$diffLatitude = $other->getLatitude() - $this->latitude;
$diffLongitude = $other->getLongitude() - $this->longitude;
$a = sin($diffLatitude / 2) * sin($diffLatitude / 2) +
cos($this->latitude) * cos($other->getLatitude()) *
sin($diffLongitude / 2) * sin($diffLongitude / 2);
$c = 2 * asin(sqrt($a));
$distance = $radiusOfEarth * $c;
return $distance;
}
}
class bigcity
{
public $name;
public $lat;
public $long;
function __construct($name,$lat,$long)
{
$this->name=$name;
$this->lat=$lat;
$this->long=$long;
}
}
function getbigcities()
{
$bigcities = array();
$bigcities[] = new bigcity('Amsterdam',52.374 ,4.89);
$bigcities[] = new bigcity('Eindhoven',51.441 ,5.478);
$bigcities[] = new bigcity('Groningen',53.219 ,6.567);
return $bigcities;
}
function findCity($lat, $lng)
{
$userinput = new POI($lat,$lng);
$bigcities = getbigcities();
$distance = 1000000000;
$result = '';
foreach ($bigcities as $bigcity)
{
$delta = $userinput->getDistanceInMetersTo(new POI($bigcity->lat,$bigcity->long));
if($delta<$distance)
{
$result = $bigcity->name;
$distance = $delta;
}
}
return ($result);
}
echo findcity(51.556,5.091); //tilburg
echo findcity(52.55,6.15); //leeuwaarden
echo findcity(52.091,5.122); //utrecht
exit;
For those struggling with the same problem, I made some Java code which scrapes continents, countries, cities, lat and lon coordinates from a website. The code isn't beautiful because I made it in a rush, but it does what it's supposed to do:
public class Main {
private static String title;
private static String land;
private static Document docu;
private static String continent = "Africa";
public static void main(String[] args) throws IOException {
String url = "http://www.timegenie.com/latitude_and_longitude/";
Document doc = Jsoup.connect(url).get();
Elements links = doc.select("a[href]");
//print("\nLinks: (%d)", links.size());
for (Element link : links) {
if (link.attr("abs:href").contains("country_coordinates")) {
try {
docu = Jsoup.connect(link.attr("abs:href")).get();
title = docu.title();
land = (trim(link.text(), 50));
if (land.equals("Algeria")) {
continent = "Africa";
} else if (land.equals("Antarctica")) {
continent = "Antarctica";
} else if (land.equals("Afghanistan")) {
continent = "Asia";
} else if (land.equals("Bouvet Island")) {
continent = "Antartica";
} else if (land.equals("Anguilla")) {
continent = "North America";
} else if (land.equals("Belize")) {
continent = "North America";
} else if (land.equals("Armenia")) {
continent = "Asia";
} else if (land.equals("Åland Islands") || land.equals("Aland Islands")) {
continent = "Europe";
} else if (land.equals("Bassas da India")) {
continent = "Africa";
} else if (land.equals("Akrotiri")) {
continent = "Asia";
} else if (land.equals("Bermuda")) {
continent = "North America";
} else if (land.equals("Clipperton Island")) {
continent = "North America";
} else if (land.equals("Argentina")) {
continent = "South America";
} else if (land.equals("American Samoa")) {
continent = "Oceania";
}
Element table = docu.select("table.times").get(0);
Elements trs = table.select("tr");
Iterator trIter = trs.iterator();
boolean firstRow = true;
while (trIter.hasNext()) {
Element tr = (Element) trIter.next();
if (firstRow) {
firstRow = false;
continue;
}
Elements tds = tr.select("td");
Iterator tdIter = tds.iterator();
int tdCount = 1;
String city = null;
String longgr = null;
String latgr= null;
while (tdIter.hasNext()) {
Element td = (Element) tdIter.next();
switch (tdCount++) {
case 1:
city = td.select("a").text();
break;
case 4:
latgr= td.text();
break;
case 6:
longgr = td.text();
break;
}
}
System.out.println(continent + "|" + land + "|" + city + "|" + latgr+ "|" + longgr+ "|");
}
} catch (Exception ex) {
Elements links2 = docu.select("a[href]");
for (Element link2 : links2) {
if (link2.attr("abs:href").contains("state_coordinates")) {
try {
try {
docu = Jsoup.connect(link2.attr("abs:href")).get();
title = docu.title();
Element table = docu.select("table.times").get(0);
Elements trs = table.select("tr");
Iterator trIter = trs.iterator();
boolean firstRow = true;
while (trIter.hasNext()) {
Element tr = (Element) trIter.next();
if (firstRow) {
firstRow = false;
continue;
}
Elements tds = tr.select("td");
Iterator tdIter = tds.iterator();
int tdCount = 1;
String city = null;
String longgr = null;
String latgr= null;
while (tdIter.hasNext()) {
Element td = (Element) tdIter.next();
switch (tdCount++) {
case 1:
city = td.select("a").text();
break;
case 4:
latgr= td.text();
break;
case 6:
longgr= td.text();
break;
}
}
System.out.println(continent + "|" + land + "|" + city + "|" + latgr+ "|" + longgr+ "|");
}
} catch (Exception e) {
e.printStackTrace();
}
} catch (Exception x) {
x.printStackTrace();
}
}
}
}
}
}
}
private static void print(String msg, Object... args) {
System.out.println(String.format(msg, args));
}
private static String trim(String s, int width) {
if (s.length() > width) {
return s.substring(0, width - 1) + ".";
} else {
return s;
}
}
}
I've used the Jsoup library.
It will take a while (around 3 minutes) to run this code, it will return a lot of lines (pasted in word: 146 pages) formatted like: continent|country|city|lat|long| so it will be easy to insert them in a database.
Cheers