Get single value from array - Array fetch from URL - php

Hi i am trying to fetch single value from below Array example -
i want to fetch order_id and name -
<?php
$url = 'http://example.com/index.php?route=feed/rest_api/orders&key=test219';
$json = file_get_contents($url);
echo '<pre>'; echo $json; echo '</pre>';
?>
Array showing
Array
(
[0] => Array
(
[order_id] => 6
[name] => zoraya panansar
[status] => Complete
[date_added] => 2014-01-24 23:06:09
[products] => 4
[total] => 14.8000
[address_1] => 345 goldhawk road
[address_2] => hammersmith
[city] => london
[Postcode] => w6 0wz
[Country] => United Kingdom
[Email] => zpanansar#yahoo.com
[Tele.] => 0786870150
)
I already tried
echo $json->order_id;
and
echo $json[0]['order_id'];
but its not working... Please help

index.php is returning wrong data, if you look closer then you will see it is trying to send success = false result as json data but probably for testing purposes, it is also returning array content directly before the json data.
Besides, if this is supposed to be a json result then you need to use json_decode before using the returned json object as a class object like $json->order_id.
This is what I get when I try your current URL With the parameters you provided: Look at the last line:
Array
(
[0] => Array
(
[order_id] => 6
[name] => zoraya panansar
[status] => Complete
[date_added] => 2014-01-24 23:06:09
[products] => 4
[total] => 14.8000
[address_1] => 345 goldhawk road
[address_2] => hammersmith
[city] => london
[Postcode] => w6 0wz
[Country] => United Kingdom
[Email] => zpanansar#yahoo.com
[Tele.] => 0786870150
)
[1] => Array
(
[order_id] => 5
[name] => ciria ann nuqui
[status] => Complete
[date_added] => 2014-01-24 17:58:36
[products] => 7
[total] => 36.4000
[address_1] => 345 goldhawk road
[address_2] => hammersmith
[city] => london
[Postcode] => w6 0wz
[Country] => United Kingdom
[Email] => joycernuqui#yahoo.com
[Tele.] => 07515732291
)
)
{"success":false}

You can not access the data that the server is returning. Instead of returning you a json object, the server is returning you the print_r() output over an array.
If its your server, then stop the print, and use json_encode() over the array before printing.
If it's not your server, then you have to parse the values from the text. You can use preg_match_all() for this.
preg_match_all("/\[order_id\] => ([^\n\r]+)/", $json, $m);
print_r($m[1]);
There may be built-in php function that can take such print_r() output and revert back into a php array, but I don't know about it!

Change the response from the url to json (Use json_encode function)
The last Row in url script should be
echo json_encode($some_array);
And than if you want the content:
$array = json_decode(file_get_contents($url),TRUE);
if(!is_array($array)){
echo 'bad response';
exit();
}
var_dump($array);
echo $array[0]['order_id'];

Related

how to display json output in my codeigniter view?

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.

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

Access array elements from API

For the life of me I can not figure out how to access the values of this array. Every example the stdClass Object has some type of value. If I try for example $obj->0->0->city; I get an error.
Can someone show me a example how to access [city] => toronto or even [date_created] => 2011-05-03 14:33:58?
I also tried this with no luck.
$object = $buy[1];
$title = $object->title[0];
echo "$title";
Thanks
This is what the api gives me.
stdClass Object
(
[id] => 1
[name] => toronto
[date_modified] => 2011-03-08 13:07:10
[tax_rate_provincial] =>
)
<br/>
Array
(
[0] => stdClass Object
(
[0] => stdClass Object
(
[id] => 28131844
[full_date] => 20110506
[end_date] => 20110511
[city] => toronto
[saved] => 1651
[discount_percentage] => 52
[deal_option] => Array
(
[0] => stdClass Object
(
[id] => 2600
[title] =>
[date_modified] => 0000-00-00 00:00:00
[date_created] => 2011-05-03 14:33:58
[value] => 3150
[price] => 1499
[deal_id] => 28131844
[is_default] => 0
)
)
[options] =>
[option_quantity] =>
[option_remaining] =>
[purchase_limit] => 1
[gift_limit] => 0
There is a special evil syntax to bypass numeric object attributes:
print $obj->{'0'}->{'0'}->city;
Is the correct syntax, and equivalent to the path you already determined.
Your second example is an array however, so it's probably:
print $array[0]->{'0'}->city;
The alternative is always to just foreach over a specific level - that works for objects and arrays likewise.

Categories