PHP: How to parse a stdClass Object? - php

I'm trying to parse this data that is returned from SmartyStreets (it's an address verification company).
Here is an example:
Array
(
[0] => stdClass Object
(
[input_index] => 0
[candidate_index] => 0
[delivery_line_1] => 3785 Las Vegas Blvd S
[last_line] => Las Vegas NV 89109-4333
[delivery_point_barcode] => 891094333992
[components] => stdClass Object
(
[primary_number] => 3785
[street_name] => Las Vegas
[street_postdirection] => S
[street_suffix] => Blvd
[city_name] => Las Vegas
[state_abbreviation] => NV
[zipcode] => 89109
[plus4_code] => 4333
[delivery_point] => 99
[delivery_point_check_digit] => 2
)
[metadata] => stdClass Object
(
[record_type] => H
[county_fips] => 32003
[county_name] => Clark
[carrier_route] => C024
[congressional_district] => 01
[building_default_indicator] => Y
[rdi] => Commercial
[latitude] => 36.10357
[longitude] => -115.17295
[precision] => Zip9
)
[analysis] => stdClass Object
(
[dpv_match_code] => D
[dpv_footnotes] => AAN1
[dpv_cmra] => N
[dpv_vacant] => N
[active] => Y
[footnotes] => B#H#L#M#
)
)
)
I'm new to working in Objects, so I'm having difficulty understanding how this works. From the above print_r $result output, I'm trying to access [delivery_line1], [city_name], [state_abbreviation], [zipcode] and [plus4_code].
How do I access this tree in PHP?
I've tried this:
echo $result["delivery_line_1"];
But that gives "Undefined index: delivery_line_1".
echo $result->delivery_line_1;
But that gives "Trying to get property of non-object".
What am I missing? Thanks!

$result[0]->delivery_line_1;
$result is an array containing an object.

Related

How to display data in this format from multiple associative array php

I'm trying to find out in a simple way to display a clean like this format
Having a hard time to spread the data in this associative array got this from an API
Array (
[wind] => Array (
[speed] => 5
[direction] => North West
[directionDegrees] => 310
[unit] => KT
)
[visibility] => Array (
[mainVisibility] => 10SM
)
[clouds] => Array (
[0] => Array (
[height] => 25000
[quantity] => few
)
)
[cavok] =>
[remark] => automated station with a precipitation discriminator sea level pressure of 1021.7 HPa hourly temperature of 17.2°C and dew point of -1.1°C
[day] => 6
[time] => 22:52:00
[airport] => Array (
[name] => Hartsfield Jackson Atlanta International Airport
[city] => Atlanta
[country] => Array (
[name] => United States
)
[iata] => ATL
[icao] => KATL
[latitude] => 33.6367
[longitude] => -84.428101
[altitude] => 1026
[timezone] => -5
[dst] => A
)
[message] => KATL 062252Z 31005KT 10SM FEW250 17/M01 A3017 RMK AO2 SLP217 T01721011
[station] => KATL
[temperature] => 17
[dewPoint] => -1
[altimeter] => 1021
[nosig] =>
[auto] =>
[amendment] =>
[nil] =>
[corrected] =>
[cancelled] =>
)
I'm not good at programming as this is our assignment from our school I'm looking at to loop the array but I can't seem to find a way how to do it.
You can use this parser source code and make your own solution on the base
https://github.com/SafranCassiopee/php-metar-decoder
or simple way to get field
$arr = '$yourDataArrayHere$';
$metarRw = $arr['message']
echo 'Metar message '.$metarRw;
$airportName = $arr['airport']['name']
echo 'Airport name '.$airportName;
etc.

How to Separate PHP Object

I am confused on how to separate the following output into separate variables. Here is the array I am working with:
stdClass Object ( [FlightInfoExResult] => stdClass Object ( [next_offset] => 1 [flights] => stdClass Object ( [faFlightID] => UAL1-1489818347-airline-0169 [ident] => UAL1 [aircrafttype] => B789 [filed_ete] => 17:05:00 [filed_time] => 1489818347 [filed_departuretime] => 1490074200 [filed_airspeed_kts] => 430 [filed_airspeed_mach] => [filed_altitude] => 0 [route] => [actualdeparturetime] => 0 [estimatedarrivaltime] => 1490136300 [actualarrivaltime] => 0 [diverted] => [origin] => KSFO [destination] => WSSS [originName] => San Francisco Intl [originCity] => San Francisco, CA [destinationName] => Singapore Changi [destinationCity] => Singapore ) ) )
I am outputting this through the FlightAware API system. Here is the code I am using to output the above:
$params = array("ident" => "UAL1","howMany" => 1,"offset" => 0 );
$result = $client->FlightInfoEx($params);
print_r($result);
Here is an example of how I would like it to seperate the object:
UAL1,B789 ect.
First of all that's not an array your working with, it is an object.
To access it's properties use the -> syntax, i.e.
$flightInfoExResult = $result->FlightInfoExResult;
You can then access the next_offset property with
flightInfoExResult->next_offset; and so on.

Handling JSON response from cURL

I am trying to get data from an address verification API I use, and I'm having trouble getting data from it. I have no problem cURLing the addresses and getting a response, but I need help with PHP handling the response.
JSON structure:
[
{ "input_index": 0,
"candidate_index": 0,
"addressee": "Apple Inc",
"delivery_line_1": "1 Infinite Loop",
"delivery_line_2": "PO Box 42",
"last_line": "Cupertino CA 95014-2083",
"delivery_point_barcode": "950142083017",
"metadata": {
"latitude":"48.12685",
"longitude":"-39.16847"
},
}
{ "input_index": 1,
"candidate_index": 0,
"addressee": "Google Inc",
"delivery_line_1": "1600 Amphitheater Pkwy",
"delivery_line_2": "",
"last_line": "Mountain View CA 94043-1351",
"delivery_point_barcode": "950142083017",
"metadata": {
"latitude":"48.12685",
"longitude":"-39.16847"
},
}
]
My code:
$response = curl_exec($ch);
curl_close($ch);
$rd = json_decode($response);
echo $rd->metadata[0]->latitude;
But then I get the error of Trying to get property of non-object.
What am I doing wrong?
EDIT:
print_r($rd); gives me:
Array ( [0] => stdClass Object ( [input_index] => 0 [candidate_index]
=> 0 [addressee] => Randolph Gray [delivery_line_1] => 8758 Sunset Breeze Dr [last_line] => Reno NV 89506-4136 [delivery_point_barcode]
=> 895064136585 [components] => stdClass Object ( [primary_number] => 8758 [street_name] => Sunset Breeze [street_suffix] => Dr [city_name]
=> Reno [state_abbreviation] => NV [zipcode] => 89506 [plus4_code] => 4136 [delivery_point] => 58 [delivery_point_check_digit] => 5 ) [metadata] => stdClass Object ( [record_type] => S [zip_type] => Standard [county_fips] => 32031 [county_name] => Washoe [carrier_route] => C038 [congressional_district] => 02 [rdi] => Residential [elot_sequence] => 0381 [elot_sort] => A [latitude] =>
39.63353 [longitude] => -119.89745 [precision] => Zip9 [time_zone] => Pacific [utc_offset] => -8 [dst] => 1 ) [analysis] => stdClass Object ( [dpv_match_code] => Y [dpv_footnotes] => AABB [dpv_cmra] => N [dpv_vacant] => N [active] => Y ) ) [1] => stdClass Object ( [input_index] => 1 [candidate_index] => 0 [addressee] => Julio Valdez [delivery_line_1] => 7464 Gannon Dr [last_line] => Reno NV 89506-3186 [delivery_point_barcode] => 895063186644 [components] => stdClass Object ( [primary_number] => 7464 [street_name] => Gannon [street_suffix] => Dr [city_name] => Reno [state_abbreviation] => NV [zipcode] => 89506 [plus4_code] => 3186 [delivery_point] => 64 [delivery_point_check_digit] => 4 ) [metadata] => stdClass Object ( [record_type] => S [zip_type] => Standard [county_fips] => 32031 [county_name] => Washoe [carrier_route] => C038 [congressional_district] => 02 [rdi] => Residential [elot_sequence] => 0048 [elot_sort] => A [latitude] => 39.62646 [longitude] => -119.89913 [precision] => Zip9 [time_zone] => Pacific [utc_offset] => -8 [dst] => 1 ) [analysis] => stdClass Object ( [dpv_match_code] => Y [dpv_footnotes] => AABB [dpv_cmra] => N [dpv_vacant] => N [active] => Y ) ) [2] => stdClass Object ( [input_index] => 2 [candidate_index] => 0 [addressee] => Nicholas Carone [delivery_line_1] => 8685 Bagpipe Cir [last_line] => Reno NV 89506-4165 [delivery_point_barcode] => 895064165853 [components] => stdClass Object ( [primary_number] => 8685 [street_name] => Bagpipe [street_suffix] => Cir [city_name] => Reno [state_abbreviation] => NV [zipcode] => 89506 [plus4_code] => 4165 [delivery_point] => 85 [delivery_point_check_digit] => 3 ) [metadata] => stdClass Object ( [record_type] => S [zip_type] => Standard [county_fips] => 32031 [county_name] => Washoe [carrier_route] => C038 [congressional_district] => 02 [rdi] => Residential [elot_sequence] => 0227 [elot_sort] => A [latitude] =>
39.63367 [longitude] => -119.89965 [precision] => Zip9 [time_zone] => Pacific [utc_offset] => -8 [dst] => 1 ) [analysis] => stdClass Object ( [dpv_match_code] => Y [dpv_footnotes] => AABB [dpv_cmra] => N [dpv_vacant] => N [active] => Y ) ) )
Invalid JSON:
"metadata": {
"latitude":"48.12685",
"longitude":"-39.16847
} ...
should be:
"metadata": {
"latitude":"48.12685",
"longitude":"-39.16847"
} ...
Mind the closing " on the longitude value.
furthermore, the two entries need to be separated by ,:
[
{ "input_index": 0,
...
},
{ "input_index": 1,
...
}
]
finally: what you get is an array of objects - not an object with arrays:
$rd[0]->metadata->latitude ...

Retrieve a value from a SimpleXML object

Excuse me for asking such a "noob" question, but I have been trying to find a simple example of how to loop through my returned xml for the past few hours and I'm getting no where. I just want to be able to cycle through the xml and pull the 'Amount' attribute and 'AmazonOrderId' attribute for each Order. I don't know how to loop, nor how to grab the pertinent data.
SimpleXMLElement Object
(
[ListOrdersResult] => SimpleXMLElement Object
(
[Orders] => SimpleXMLElement Object
(
[Order] => Array
(
[0] => SimpleXMLElement Object
(
[ShipmentServiceLevelCategory] => SecondDay
[OrderTotal] => SimpleXMLElement Object
(
[Amount] => 5.93
[CurrencyCode] => USD
)
[SellerOrderId] => 107-1261608-7067458
[FulfillmentChannel] => AFN
[BuyerEmail] => 5qhs64ktb88pdsj#marketplace.amazon.com
[OrderStatus] => Shipped
[BuyerName] => Derrick D Vann
[ShipServiceLevel] => SecondDay
[LastUpdateDate] => 2013-03-13T02:20:31Z
[PurchaseDate] => 2013-03-11T06:14:40Z
[NumberOfItemsUnshipped] => 0
[MarketplaceId] => ATVPDKIKX0DER
[SalesChannel] => Amazon.com
[ShippingAddress] => SimpleXMLElement Object
(
[Phone] => 202 746-2567
[PostalCode] => 20001-4040
[Name] => Derrick Vann
[CountryCode] => US
[StateOrRegion] => DC
[AddressLine1] => 2120 Vermont Ave NW Apt 117
[City] => Washington
)
[NumberOfItemsShipped] => 1
[AmazonOrderId] => 107-1261608-7067458
[PaymentMethod] => Other
)
[1] => SimpleXMLElement Object
(
[ShipmentServiceLevelCategory] => Expedited
[OrderTotal] => SimpleXMLElement Object
(
[Amount] => 23.30
[CurrencyCode] => USD
)
[SellerOrderId] => 104-9066827-4446667
[FulfillmentChannel] => AFN
[BuyerEmail] => 6kfc88nrsnm83fq#marketplace.amazon.com
[OrderStatus] => Shipped
[BuyerName] => Quoc Bui
[ShipServiceLevel] => Expedited
[LastUpdateDate] => 2013-03-13T09:34:26Z
[PurchaseDate] => 2013-03-11T08:07:13Z
[NumberOfItemsUnshipped] => 0
[MarketplaceId] => ATVPDKIKX0DER
[SalesChannel] => Amazon.com
[ShippingAddress] => SimpleXMLElement Object
(
[Phone] => (02) 9560 3639
[PostalCode] => 2204
[Name] => Quoc Minh Bui
[CountryCode] => AU
[StateOrRegion] => New South Wales
[AddressLine1] => 19 Centennial St
[City] => Marrickville
)
[NumberOfItemsShipped] => 1
[AmazonOrderId] => 104-9066827-4446667
[PaymentMethod] => Other
)
...
SimpleXML is just great, isn't it?
foreach ($xml->ListOrdersResult->Orders->Order as $order) {
$amazonOrderId = (string) $order->AmazonOrderId;
$orderTotal = (string) $order->OrderTotal->Amount;
}
I use (string) type casting because you'd get SimpleXMLElements back for those scalar values otherwise.
pull the 'Amount' attribute and 'AmazonOrderId' attribute for each Order.
If I take you word-by-word, then this is what you're looking for:
$allThoseAttributes = $xml->xpath('//Order/#Amount|//Order/#AmazonOrderId');
However, more likely you're looking for:
$orders = [];
foreach ($xml->xpath('//Order') as $order) {
$orders[] = [
'amazon' => (string) $order->AmazonOrderId
'total' => (string) $order->OrderTotal->Amount;
];
}
because what you call attributes are infact elements. If you want to learn more about XML and Xpath, this is a good read: XPath

how to display individual values?

I get this from print_r($data):
Array (
[0] => Array (
[0] => stdClass Object (
[cto_office_id] => 1
[office_name] => Airtel India
[address_line1] => Bendoor well
[phone_office1] => 12345678912
[phone_office2] => 789451234512
[address_line2] => Kankanady Circle
[city] => Mangluru
[state] => Haryana
[pin_code] => 002
[country] => India
[web_url] => airte.co.in
[office_quote] => Office
[date_registered] => 2011-11-24 05:59:51
[bill_mail_id] => 15612561
[bill_mail_id_type] =>
[acc_status] => enabled
[comments] =>
[is_account_deleted] => 0
[account_deleted_date] => 0000-00-00 00:00:00
)
)
)
I tried this $data['phone_office1'], but that does not work.
You have an object that is nested inside two arrays. You can get it out like this:
$data[0][0]->phone_office1

Categories