PHP and JSON from Openstreetmap search - php

I am trying to use Openstreetmap and PHP to point to a place on a map.
As you can see below, I retrieve a JSON array, but PHP returns a NULL value.
Note that my $url is a valid JSON (you can check it here).
<?
$url = 'http://nominatim.openstreetmap.org/search/Piazza%20Duomo%20Trento?format=json&addressdetails=1&limit=1&polygon_svg=1';
$html = file_get_contents($url);
$jsonout = json_decode($html);
echo $jsonout[0];
?>
What am I doing wrong?

What am I doing wrong?
First of all, your openning tag is not correct :
<? ----> <?php
Then, you cannot echo an array like that. Use var_dump on your array to see the structure.
When I try your code with the corrections, I got this :
array (size=1)
0 =>
object(stdClass)[1]
public 'place_id' => string '8577656' (length=7)
public 'licence' => string 'Data © OpenStreetMap contributors, ODbL 1.0. http://www.openstreetmap.org/copyright' (length=84)
public 'osm_type' => string 'node' (length=4)
public 'osm_id' => string '924463183' (length=9)
public 'boundingbox' =>
array (size=4)
0 => string '46.0675164' (length=10)
1 => string '46.0676164' (length=10)
2 => string '11.1217498' (length=10)
3 => string '11.1218498' (length=10)
public 'lat' => string '46.0675664' (length=10)
public 'lon' => string '11.1217998' (length=10)
public 'display_name' => string 'Piazza Duomo, Piazza del Duomo, centro storico Trento, Trento, TN, TAA, 38122, Italia' (length=85)
public 'class' => string 'highway' (length=7)
public 'type' => string 'bus_stop' (length=8)
public 'importance' => float 0.311
public 'icon' => string 'http://nominatim.openstreetmap.org/images/mapicons/transport_bus_stop2.p.20.png' (length=79)
public 'address' =>
object(stdClass)[2]
public 'bus_stop' => string 'Piazza Duomo' (length=12)
public 'pedestrian' => string 'Piazza del Duomo' (length=16)
public 'suburb' => string 'centro storico Trento' (length=21)
public 'city' => string 'Trento' (length=6)
public 'county' => string 'TN' (length=2)
public 'state' => string 'TAA' (length=3)
public 'postcode' => string '38122' (length=5)
public 'country' => string 'Italia' (length=6)
public 'country_code' => string 'it' (length=2)
public 'svg' => string 'cx="11.1217998" cy="-46.067566399999997"' (length=40)

In answer to your question, except for trying to output an array with the following statement
echo $jsonout[0];
Which will throw a Catchable fatal error: Object of class stdClass could not be converted to string
Everything is ok.
If this is about accessing the members of the json_decode return, see below
$jsonout is an array with one element,
that one element is an object, you can access its members like this
print $jsonout[0]->licence;
Which will output
Data © OpenStreetMap contributors, ODbL 1.0. http://www.openstreetmap.org/copyright
If you'd like an associative array, you can pass the second argument for json_decode, like this
$jsonout = json_decode($html,true);
print $jsonout[0]['display_name'];
Which will decode the json into an associative array and will display in a similar way
Piazza Duomo, Piazza del Duomo, centro storico Trento, Trento, TN, TAA, 38122, Italia

please use print_r() in place of echo
$url = "http://nominatim.openstreetmap.org/search/Piazza%20Duomo%20Trento?format=json&addressdetails=1&limit=1&polygon_svg=1";
$html = file_get_contents($url);
$jsonout = json_decode($html);
print_r($jsonout[0]);
and you will get your result.

or you can print $jsonout[0]["license"]

Related

Why is the array index is undefined undefined?

I'm having trouble finding out why is the following code not working.
I've a JSON answer from a remote server, containting the following data:
...., "UserId":{"50423":"Free Kkludkjta","54379":"Sjkllyu\u00e9lkj Nolla","67103":"Tswt\u00f3 BLLA","64469":"Uz\u00e1h G","46699":"RT\u00e1sdt UTSF","46873":"Tam\u00e1s XXXX"}, ...
(names are swapped, but since there are some special chars in the aswer I've kept those)
And I have the following code sniplet, which gives 'array index undefined for idx 64469':
$proj_schema = json_decode($proj_schema);
var_dump($proj_schema->UserId);
$avail_users = (array)$proj_schema->UserId;
var_dump($avail_users);
var_dump($avail_users[64469]);
The output is the following:
C:\wamp\www\j34\administrator\components\com_mycomponent\views\myview\view.html.php:113:
object(stdClass)[309]
public '50423' => string 'Name1' (length=14)
public '54379' => string 'Name2' (length=18)
public '67103' => string 'Name3' (length=12)
public '64469' => string 'Name4' (length=15)
public '46699' => string 'Name5' (length=11)
public '46873' => string 'Name6' (length=12)
C:\wamp\www\j34\administrator\components\com_mycomponent\views\myview\view.html.php:115:
array (size=6)
'50423' => string 'Name1' (length=14)
'54379' => string 'Name2' (length=18)
'67103' => string 'Name3' (length=12)
'64469' => string 'Name4' (length=15)
'46699' => string 'Name5' (length=11)
'46873' => string 'Name6' (length=12)
Notice: Undefined offset: 64469 in C:\wamp\www\j34\administrator\components\com_mycomponent\views\myview\view.html.php on line 116
If I walk through the array with foreach and write out the element based on 'if ($key == 64469)' it echos the name, but I cannot access the name by array key.
Results are same with PHP 5.6.32 (I know) and PHP 7.1.0. Result is the same if I put the id in "" or '';
What am I missing with the casting?
You are using the JSON as an object and not as an array. Therefore, the key does not exist, because it is a property.
Decode with true as 2nd argument to get an array instead of an object.
$proj_schema = json_decode($proj_schema, true);

Displaying data from MaasApi - object

As the title says I'm trying to display data here is my code
$mars_temperature = new MaasApi();
$data=$mars_temperature->getLatest();
var_dump($data);
echo $data['sol'];
error Fatal error: Cannot use object of type stdClass as array on the last line and here is var_dump:
object(stdClass)[3]
public 'terrestrial_date' => string '2015-02-09' (length=10)
public 'sol' => int 893
public 'ls' => float 287
public 'min_temp' => float -72
public 'min_temp_fahrenheit' => float -97.6
public 'max_temp' => float 2
public 'max_temp_fahrenheit' => float 35.6
public 'pressure' => float 890
public 'pressure_string' => string 'Higher' (length=6)
public 'abs_humidity' => null
public 'wind_speed' => null
public 'wind_direction' => string '--' (length=2)
public 'atmo_opacity' => string 'Sunny' (length=5)
public 'season' => string 'Month 10' (length=8)
public 'sunrise' => string '2015-02-09T12:23:00Z' (length=20)
public 'sunset' => string '2015-02-10T00:39:00Z' (length=20)
Update:
Here is also the code for API : https://github.com/dbough/MaasApi/blob/master/MaasApi.php
To access object properties, use the object operator: ->.
echo $data->sol;
To echo the properties that you referenced in your comment, use:
echo $data->max_temp;
echo $data->min_temp;

Retrieving view data in a view composer

If I do the following in this view composer:
View::composer('product.edit', function($view)
{
$viewdata = $view->getData();
dd($viewdata);
});
I can see in the output that exists 'language_id', however I don't know how to retrieve it, since $viewdata['language_id'] will throw an exception.
How should I go about this?
Update:
The accepted answer led me to discover that when a presenter is involved in this operation, the model will be available in the offset, here is the final code:
View::composer('product.edit', function($view)
{
$data = $view->offsetGet('product')->toArray();
echo $data['language_id'];
exit;
});
You may try this:
$language_id = $view->offsetGet('language_id');
Following public methods are available in the $view object (An instance of Illuminate\View\View)
0 => string '__construct' (length=11)
1 => string 'render' (length=6)
2 => string 'renderSections' (length=14)
3 => string 'with' (length=4)
4 => string 'nest' (length=4)
5 => string 'withErrors' (length=10)
6 => string 'getEnvironment' (length=14)
7 => string 'getEngine' (length=9)
8 => string 'getName' (length=7)
9 => string 'getData' (length=7)
10 => string 'getPath' (length=7)
11 => string 'setPath' (length=7)
12 => string 'offsetExists' (length=12)
13 => string 'offsetGet' (length=9)
14 => string 'offsetSet' (length=9)
15 => string 'offsetUnset' (length=11)
16 => string '__get' (length=5)
17 => string '__set' (length=5)
18 => string '__isset' (length=7)
19 => string '__unset' (length=7)
20 => string '__call' (length=6)
21 => string '__toString' (length=10)
You may also try something like this:
if($view->offsetExists('language_id')) {
$language_id = $view->offsetGet('language_id');
}
Worth noting you can also access view data using the attribute syntax (at least starting Laravel 8):
$languageId = $view->product->language_id ?? null;

How do I check an objects property types?

Sorry for the title, I couldn't find a better way to write it =/
I am receiving a error object called ErrorBase.
If there is only one error it will return me the following:
public 'ErrorBase' =>
public 'CODIGO_ERRO' => string '1' (length=1)
public 'MENSAGEM_ERRO' => string 'Autenticação Inválida' (length=24)
public 'TIPO_ERRO' => string 'Usuario' (length=7)
But if there is more than one error, it will return me a array of objects like this:
public 'ErrorBase' =>
array
0 =>
object(stdClass)[30]
public 'CODIGO_ERRO' => string '1' (length=1)
public 'MENSAGEM_ERRO' => string 'Autenticação Inválida' (length=24)
public 'TIPO_ERRO' => string 'Usuario' (length=7)
1 =>
object(stdClass)[31]
public 'CODIGO_ERRO' => string '002' (length=3)
public 'MENSAGEM_ERRO' => string 'teste 002' (length=9)
public 'TIPO_ERRO' => string 'tipo 002' (length=8)
2 =>
object(stdClass)[32]
public 'CODIGO_ERRO' => string '003' (length=3)
public 'MENSAGEM_ERRO' => string 'teste 003' (length=9)
public 'TIPO_ERRO' => string 'tipo 003' (length=8)
3 =>
object(stdClass)[33]
public 'CODIGO_ERRO' => string '004' (length=3)
public 'MENSAGEM_ERRO' => string 'teste 004' (length=9)
public 'TIPO_ERRO' => string 'tipo 004' (length=8)
How can I work with these situations?
How do I check if there is a array of objects or only a object?
Thanks in advance for any help.
Try... is_object() and is_array()
is_array($variable) returns true if $variable contains an array, and false otherwise.
Use is_array() :
if (is_array($this->ERROR_BASE))
To test the class of an object :
if ($var instanceof ErrorBase) {
To test if it is an array :
if (is_array($var)) {
use gettype() to returns the vars type.
or use is_array/is_object to test for each

what's wrong with this php code?

Ok, the idea here is to have code that will append SF_ to all key names in an array.
I took my array (which is part of an object), flipped it, added the SF_, and flipped it back.
Somewhere in the process I lost some fields...
here's what I started with:
object(stdClass)[12]
public 'Affiliate_Code__c' => string 'XX-TXUJC3' (length=9)
public 'AltEmail__c' => string 'benny#oxpublishing.com' (length=22)
public 'City' => string 'Mobile' (length=6)
public 'Email' => string 'benny#oxpublishing.com' (length=22)
public 'Fax__c' => string '251-300-1234' (length=12)
public 'FirstName' => string 'Benny' (length=5)
public 'LastName' => string 'Butler' (length=6)
public 'Phone' => string '251-300-3530' (length=12)
public 'PostalCode' => string '36606' (length=5)
public 'State' => string 'AL' (length=2)
public 'Street' => string '851 E I-65 Service Rd' (length=21)
public 'test1__c' => float 1
array
'SF_Affiliate_Code__c' => string 'XX-TXUJC3' (length=9)
'SF_Email' => string 'benny#oxpublishing.com' (length=22)
'SF_City' => string 'Mobile' (length=6)
'SF_Fax__c' => string '251-300-1234' (length=12)
'SF_FirstName' => string 'Benny' (length=5)
'SF_LastName' => string 'Butler' (length=6)
'SF_Phone' => string '251-300-3530' (length=12)
'SF_PostalCode' => int 36606
'SF_State' => string 'AL' (length=2)
'SF_Street' => string '851 E I-65 Service Rd' (length=21)
And here's my code:
$response = $mySforceConnection->query(($query));
foreach ($response->records as $SF) {
}
var_dump($SF);
$SF = array_flip($SF);
foreach ($SF as $key => $value){
$SF[$key] = 'SF_'.$value;
}
$SF = array_flip($SF);
echo "<pre>";
var_dump($SF);
echo "</pre>";
extract($SF);
Any idea?
I'm new to OO programming of any sort, and I'm sure this has something to do with it.
I'm so stupid I have to do:
foreach ($response->records as $SF) { }
because I don't know how to get to that array any other way.
Help!
Thanks!
When you do the flip, you end up with duplicate keys - the values become the keys, and your values are not unique (e.g. Email and AltEmail__c both have the same value).
Rather than doing a flip then flipping back, just create a new array and copy the values in with the new keys:
$SF_new = array();
foreach($SF as $key => $value ) {
$SF_new['SF_' . $key] = $value;
}
// And if you want to continue using the $SF name...
$SF = $SF_new;
array_flip will flip the values and keys, as you said. A PHP array cannot have multiple keys with the same name. Try something like this to avoid flipping:
<?php
$SF = array();
foreach($response->records as $key => $value)
{
$SF['SF_' . $key] = $value;
}
About the way you get to the array in the object, this is the proper way to do it.
$SF = get_object_vars($response);
Will transform your object into an array.
flip swaps keys and values. because you have values that share the same value, you lose them in the flip.

Categories