how to display json output in my codeigniter view? - php

I am working a smole project airport search using Rapidapi but
i can't display json data from API in my codeigniter view. i'm googling meany time but not perfect result. please help
here is my json output
HttpResponse Object
(
[code:HttpResponse:private] => 200
[raw_body:HttpResponse:private] => [{"airportId":"6f576bf7-090a-46e3-be70-6d8a55275e04","code":"YYZ","name":"Toronto, Ontario","location":{"longitude":-79.63083299999998,"latitude":43.677222},"cityId":"8f65ce90-aafb-42b4-8185-ae4f1b131889","city":"Toronto","countryCode":"CA","themes":[],"pointsOfSale":["CA"]}]
[body:HttpResponse:private] => Array
(
[0] => stdClass Object
(
[airportId] => 6f576bf7-090a-46e3-be70-6d8a55275e04
[code] => YYZ
[name] => Toronto, Ontario
[location] => stdClass Object
(
[longitude] => -79.630833
[latitude] => 43.677222
)
[cityId] => 8f65ce90-aafb-42b4-8185-ae4f1b131889
[city] => Toronto
[countryCode] => CA
[themes] => Array
(
)
[pointsOfSale] => Array
(
[0] => CA
)
)
)
)
my Controller
public function AirportSearch_form(){
$url="https://cometari-airportsfinder-v1.p.rapidapi.com/api/airports/by-code?code=yyz";
$response = $this->unirest->get($url, $headers = array("X-Mashape-Key" => "ced348bae5mshd648601c9de77cbp1e2dcejsn222973a7564d", "X-Mashape-Host" => "cometari-airportsfinder-v1.p.rapidapi.com"));
//echo'<pre>';
//print_r($response);
//exit();
$jdata=json_decode($response);
$app_title=$this->SuperAdmin_model->AppDataShow();
$data['title']=$app_title->app_title;
$data['menu_col']='';
$this->load->view('agent/header',$data);
$this->load->view('flight/airport_search',$jdata);
$this->load->view('agent/footer',$data);
}

you have both json and non-json versions retrieved. as the latter doesn't require decoding i suggest you use that.
it seems like you can do $response->body[0] to get the array.
and specific items via $response->body[0]->name .etc.

Related

Find matching value from JSON with PHP Curl? [duplicate]

This question already has answers here:
PHP multidimensional array search by value
(23 answers)
Closed 4 years ago.
So I've got a page with some jSON data I want to gather into arrays with cURL. To be precise, cURL when used from a PHP program, not from the command line.
I can do that part well with the following codeblock below:
$token = 'my_token_here';
$headers = ['Authorization: Bearer ' . $token];
$curl = curl_init();
curl_setopt_array($curl, [
CURLOPT_RETURNTRANSFER => true,
CURLINFO_HEADER_OUT => true,
CURLOPT_URL => 'https://my.infrastructure.com/api/v1/accounts/search',
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_SSL_VERIFYPEER => true,
CURLOPT_HTTPHEADER => $headers
]);
$resp = curl_exec($curl);
curl_close($curl);
$data = json_decode($resp);
dd($data);
This will return me a 2D array of all the accounts on the page in the above URL, each array containing an 'account' with variables like ID, name, etc.
The printed output, should I run "print_r($data)", is this:
Array ( [0] => stdClass Object ( [id] => 130375 [name] => 3Lakes [domain] => 3lakes.instructure.com [distance] => [authentication_provider] => google ) [1] => stdClass Object ( [id] => 130376 [name] => 3Lakes - Parents [domain] => 3lakes.instructure.com [distance] => [authentication_provider] => canvas ) [2] => stdClass Object ( [id] => 126425 [name] => 95 Percent Group [domain] => 95percentgroup.instructure.com [distance] => [authentication_provider] => ) [3] => stdClass Object ( [id] => 129409 [name] => AACM [domain] => aacm.instructure.com [distance] => [authentication_provider] => canvas ) [4] => stdClass Object ( [id] => 129272 [name] => Aalen [domain] => aalen.instructure.com [distance] => [authentication_provider] => canvas ) [5] => stdClass Object ( [id] => 129572 [name] => Aaron Cohn Middle School - MCSD [domain] => mcsd.instructure.com [distance] => [authentication_provider] => ldap ) [6] => stdClass Object ( [id] => 128124 [name] => Abilene Christian University [domain] => acu.instructure.com [distance] => [authentication_provider] => ) [7] => stdClass Object ( [id] => 127204 [name] => Abilene Christian University Online [domain] => acuonline.instructure.com [distance] => [authentication_provider] => ) [8] => stdClass Object ( [id] => 130398 [name] => Abington Public Schools [domain] => abington.instructure.com [distance] => [authentication_provider] => canvas ) [9] => stdClass Object ( [id] => 128797 [name] => Academia Virtual [domain] => canvas.academiavirtual.cr [distance] => [authentication_provider] => ) )
Now, instead of doing all that, I just want to collect a single array, where that array has an ID equal to an ID I give it; i.e if I want to find the ID "15", it returns either the array matching that, or null.
I am not sure how, though. I know that, after the query, I can do PHP to comb the retrieved $data and check each, but I want to do this a bit smoother, presumably in the curl_setopt_array area somehow.
Is what I'm trying to do possible in this way? Any advice?
Your confusing some things here.
cURL has no effect on the data format that is transported because its a library for networking.
You already got the solution, looping over the array and restructure the data to your needs.
Also you dont have a 2D array but an array of stdClass objects.
So first of all if you want to have an 2d array you should pass true as the 2nd argument to json_decode to make it parse JSON-objects into associative arrays instead of stdClass.
Then you use a foreach loop and map your entries by id:
$mappedData = [];
foreach ($data as $item) {
$mappedData[$item->id] = $item; //Or $mappedData[$item["id"]] if assoc
}
There may be some fancy callback methods using array_map etc. but the foreach loop is the simplest (in my opinion).

Working with results of api in json array

I am using json to process a 3rd party api based on post code results. So far I have got
$json = json_decode(file_get_contents($remote_url, false, $context))
which provides the following results from a print_r:
stdClass Object ( [result] => stdClass Object ( [copyrightNotice] => © 2013-2014 StreetCheck. All Rights Reserved. Contains Ordnance Survey, Royal Mail, National Statistics and Land Registry data © Crown copyright and database right 2014. [postcode] => SN5 5RF [point] => stdClass Object ( [latitude] => 51.564896985 [longitude] => -1.837017086 ) [street] => Percheron Close [street2] => [locality] => Shaw [locality2] => [postTown] => Swindon [fullLocation] => Percheron Close, Shaw, Swindon, SN5 5RF [country] => England [outputArea] => E00078711 [largeUser] => [active] => 1 [ward] => stdClass Object ( [code] => E05002164 [name] => Shaw and Nine Elms ) [constituency] => stdClass Object ( [code] => E14000947 [name] => South Swindon ) [region] => stdClass Object ( [code] => E15000009 [name] => South West ) [commentary] => Percheron Close in Shaw is in the South West region of England. The postcode is within the Shaw and Nine Elms ward/electoral division, which is in the constituency of South Swindon. [urbanClassification] => Urban ) [message] => OK [success] => 1 )
Where the code above is the result from json.
How do I set the value of postcode to $postcode...
I have tried:
$postcode = $json['result']['postcode'] or [0]['postcode']
and got Fatal error:
Cannot use object of type stdClass as array in.
Could someone put me on right path please.
These are standard objects not arrays.
$json->result->postcode
if you want to keep your code the same, convert to php array.
// vvvv
$json = json_decode(file_get_contents($remote_url, false, $context), true);
this should fix you up.
As in case of your API response results in object of type stdClass.
So the result is in the form of object but not in the form of Array.
Read result like this :
<?php
$json = json_decode(file_get_contents($remote_url, false, $context));
$json->result->postcode;
?>
For reference visit : http://www.academia.edu/4092169/Get_data_from_string_with_JSON_object_in_PHP

Getting sugarcrm array output via REST api sorted with PHP correctly

First, I'm using sugarcrm pro 6.5 and accessing via rest v4, so I have this array that's being returned from printing $results that is working fine:
stdClass Object
(
[result_count] => 2000
[total_count] => 3390
[next_offset] => 2000
[entry_list] => Array
(
[0] => stdClass Object
(
[id] => 77da301b-83dd-4fe6-e38f-53ba151fb084
[module_name] => Leads
[name_value_list] => stdClass Object
(
[id] => stdClass Object
(
[name] => id
[value] => 77da301b-83dd-4fe6-e38f-53ba151fb084
)
[name] => stdClass Object
(
[name] => name
[value] => Jim Beam
)
[status] => stdClass Object
(
[name] => status
[value] => Dead
)
[website] => stdClass Object
(
[name] => website
[value] => website.com
)
[phone_cr] => stdClass Object
(
[name] => phone_cr
[value] => 1-888-888-8888
)
)
)
[1] => stdClass Object
(
[id] => d0ecc069-d556-98f3-41f2-53ba1468327a
[module_name] => Leads
[name_value_list] => stdClass Object
(
[id] => stdClass Object
(
[name] => id
[value] => d0ecc069-d556-98f3-41f2-53ba1468327a
)
[name] => stdClass Object
(
[name] => name
[value] => John Doe
)
[status] => stdClass Object
(
[name] => status
[value] => New
)
[website] => stdClass Object
(
[name] => website
[value] => web.com
)
[phone_cr] => stdClass Object
(
[name] => phone_cr
[value] => 1-888-888-8888
)
)
)
I'm using a query from the api to filter the results for the user I'm targeting:
'query' => "leads.assigned_user_id='user_ID-here'",
'order_by' => "date_entered DESC",
This works fine. So I've ran a foreach () statement to retrieve only one field on a button click, which also works just fine. What I really need to accomplish is before this statement, a foreach() command (or something else?) to filter out and retrieve ONLY the "New" results in the status value, and from that group output an array showing only the website field. Seen in the "desired end result section of this question."
This is the code I'm filtering the field I'm targeting and having a new array created with if that helps bridge the gap:
$results = call('get_entry_list', $params, $url);
$eresult = array();
foreach ($results->entry_list as $index=>$value_list) {
$listed = $value_list->name_value_list->website->value;
$eresult[] = $listed;}
So the desired end result based on this data should be:
Array
(
[1] => web.com
)
I'm unsure what I need to do to filter the "Status" field to only then be ran with the $eresult array I created to achieve this. To be clear, everything is working as it should, and my print from $eresult is outputting exactly as it should by returning all results in the website value area, I just need some help to get it sorted before going to that step by sorting it by the "new" status first without all the extra 'stuff,' then sorting out the array in my desired format with the foreach() statement above. I tried to cut out all the other code, as it's a pretty long project, so this should be all the relevant information for the particular goal I need to accomplish in this segment. Any help is greatly appreciated! Thank you!
I've decided to create a second script for this as a temp solution by adding:
'query' => "(leads.assigned_user_id='user_ID-here') AND (status='New')"
So I guess that works, I was trying to avoid calling another script for just one separate function, but it is working fine.

Getting values of a stdObject in php

I am using an API to get some values. When I print my variable returning an array from api it returns stdObject Class
This is how I request the data:
$graphObject = (new FacebookRequest( $session, 'GET', '/me?fields=id,first_name,last_name,tagged_places' ))->execute()->getGraphObject()->asArray();
This is how I am printing it:
echo '<pre>' . print_r( $graphObject, 1 ) . '</pre>';
This is what it returns:
Array
(
[id] => 111111
[first_name] => Bob
[last_name] => Stevensen
[tagged_places] => stdClass Object
(
[data] => Array
(
[0] => stdClass Object
(
[id] => 111111
[created_time] => 1905-01-01T08:00:00+0000
[place] => stdClass Object
(
[id] => 1111111
[location] => stdClass Object
(
[latitude] => 36.1313
[longitude] => -95.9373
)
[name] => Tulsa, Oklahoma
)
)
[1] => stdClass Object
(
[id] => 11111
[created_time] => 2014-05-30T21:41:11+0000
[place] => stdClass Object
(
[id] => 111111
[location] => stdClass Object
(
[city] => Okmulgee
[country] => United States
[latitude] => 35.623012460758
[longitude] => -95.972782756346
[state] => OK
[street] => 104 S Morton Ave
[zip] => 74447-5022
)
[name] => Ike's Downtown Pub & Eatery
)
)
I have found some examples of this stating the way to get a value out of this class object would be like this,
echo $graphObject->{'$STDCLASS'}->{'$FIELD I'M TRYING TO GET'};
I am swapping out these values trying to figure out what the object name is but I get this error:
Notice: Trying to get property of non-object in /file/path
What is the correct way to get the values from this stdClass Object I think maybe I am just not understanding the name of the Object Is it possible to tell from the code I have posted here?
the object contains an array called Data you can access:
foreach ($graphObject->data as $data) {
echo $data->id
}
This takes the object and should make it directly accessible
though on second thought .. you may also need to try echo $data['id']; as its not an object any more..
If that doenst work .. try :
$info = json_decode($graphObject,true);
and see if you can work the $info variable easier.

Get values from SimpleXMLElement object

I am writing that post because i'm trying to solve a problem which seems to be stupid but unfortunately i cannot make it. I have an XML file (link) which i'm parsing with simplexml_load_file($link) as below:
function getListPoints($countryCode,$nbrPoints)
{
$xml_containt_url = "http://openchargemap.org/api/?output=xml&countrycode=".$countryCode."&maxresults=".$nbrPoints;
$xml_output = simplexml_load_file($xml_containt_url);
return $xml_output;
}
So when I print the xml output:
$infos_point = getListPoints("US",2);
print($infos_point);
I get everything I want, it gives me :
SimpleXMLElement Object
(
[ChargePoint] => Array
(
[0] => SimpleXMLElement Object
(
[#attributes] => Array
(
[ID] => 2381
[UUID] => BFE199D5-07D4-4310-86D7-8BCB9092541D
[DateLastConfirmed] => 31/08/2010 00:00:00
[OperatorID] => 1
[OperatorTitle] => (Unknown Operator)
[DataProviderID] => 2
[NumberOfPoints] =>
[DataQualityLevel] => 1
[PercentageSimilarity] =>
)
[GeneralComments] => 1 SP Inductive
[AddressInfo] => SimpleXMLElement Object
(
[LocationTitle] => Sacramento County Public Garage
[AddressLine1] => 725 7th St
[AddressLine2] => SimpleXMLElement Object
(
)
[Town] => Sacramento
[StateOrProvince] => CA
[Postcode] => 95814
[Country] => United States
[Latitude] => 38.5846
[Longitude] => -121.4961
[ContactTelephone1] => 916-874-6227
[AccessComments] => 24 hours daily; pay lot
[RelatedURL] => SimpleXMLElement Object
(
)
)
The problem appears when i want to get some values of the SimpleXMLElement object, for example, I want to get the Town value, so I proceed as it follows :
$Town = $infos_point->ChargePoint[0]->AdressInfo->Town;
print($Town);
And it gives me a blank page. I have tried everything I've read on the internet and still nothing.
Maybe somebody can tell me what's happening ? it would be great as i will be able to continue my project.
It's your spelling of adDress. Should be: $Town = $infos_point->ChargePoint[0]->AddressInfo->Town;

Categories