Handling JSON response from cURL - php

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

Related

Parsing SimpleXML Object data

How to get "file_url" from this data?
Response can contain few objects, and how to parse it?
Code that I use:
<?php
$r34data = simplexml_load_file('https://rule34.xxx/index.php?page=dapi&s=post&q=index&tags=green_hair&limit=2');
print_r($r34data);
Response:
SimpleXMLElement Object ( [#attributes] => Array ( [count] => 69175 [offset] => 0 ) [post] => Array ( [0] => SimpleXMLElement Object ( [#attributes] => Array ( [height] => 2039 [score] => 1 [file_url] => https://wimg.rule34.xxx/images/3820/01e0a587f6e303c34669a4f79c994100.png [parent_id] => [sample_url] => https://rule34.xxx/samples/3820/sample_01e0a587f6e303c34669a4f79c994100.jpg [sample_width] => 850 [sample_height] => 667 [preview_url] => https://rule34.xxx/thumbnails/3820/thumbnail_01e0a587f6e303c34669a4f79c994100.jpg [rating] => e [tags] => 1boy 2girls annette_(fire_emblem) annette_fantine_dominic ass back back_view bare_back big_ass big_breasts blue_eyes blue_lingerie breasts_outside byleth_(fire_emblem) byleth_(fire_emblem)_(male) byleth_(male) ffm_threesome fingering fingering_partner fire_emblem fire_emblem:_three_houses french_kiss green_hair kissing light_blue_lingerie lingerie long_hair lysithea_(fire_emblem) lysithea_von_ordelia medium_breasts medium_hair nintendo nipples orange_hair pink_eyes purple_lingerie pussy pussy_juice pussy_juice_trail quan_ming sex threesome vaginal_penetration white_hair [id] => 4324333 [width] => 2600 [change] => 1608630074 [md5] => 01e0a587f6e303c34669a4f79c994100 [creator_id] => 503169 [has_children] => false [created_at] => Tue Dec 22 09:21:59 +0000 2020 [status] => active [source] => https://www.pixiv.net/en/artworks/86455582 [has_notes] => false [has_comments] => false [preview_width] => 150 [preview_height] => 117 ) ) [1] => SimpleXMLElement Object ( [#attributes] => Array ( [height] => 1600 [score] => 10 [file_url] => https://wimg.rule34.xxx/images/3820/4a88c87d1cb18928bcee85207bf1c61b.jpeg [parent_id] => [sample_url] => https://rule34.xxx/samples/3820/sample_4a88c87d1cb18928bcee85207bf1c61b.jpg [sample_width] => 850 [sample_height] => 618 [preview_url] => https://rule34.xxx/thumbnails/3820/thumbnail_4a88c87d1cb18928bcee85207bf1c61b.jpg [rating] => e [tags] => 1boy 1boy1girl 1girls all_fours anal anal_sex barefoot bent_over big_breasts christmas clothed_male_nude_female clothing cum cum_in_ass cum_inside cum_leaking doggy_style ejaculation ejaculation_while_penetrated faceless_male feet female female_focus forehead_protector green_hair hair_bun headband huge_breasts kneeling long_hair looking_at_viewer looking_back male multicolored_hair naked naruto naruto_(series) naruto_shippuden nude open_mouth orange_eyes orange_hair pakura penetration pussy santa_costume smile soles standing tied_hair toes two_tone_hair vagina [id] => 4324142 [width] => 2202 [change] => 1608622103 [md5] => 4a88c87d1cb18928bcee85207bf1c61b [creator_id] => 631992 [has_children] => false [created_at] => Tue Dec 22 07:28:01 +0000 2020 [status] => active [source] => [has_notes] => false [has_comments] => false [preview_width] => 150 [preview_height] => 108 ) ) ) )
Please help!
(don't ask why I parsing rule34)
Hi You can conver it to the array and work with is easy
libxml_use_internal_errors(TRUE);
$objXmlDocument = simplexml_load_file("https://rule34.xxx/index.php?page=dapi&s=post&q=index&tags=green_hair&limit=2");
if ($objXmlDocument === FALSE) {
echo "There were errors parsing the XML file.\n";
foreach(libxml_get_errors() as $error) {
echo $error->message;
}
exit;
}
$objJsonDocument = json_encode($objXmlDocument);
$arrOutput = json_decode($objJsonDocument, TRUE);
echo "<pre>";
print_r($arrOutput);

Read attribute from XML file

I am trying to read XML attributes from XML file. I want to echo baadNavn.
<?php
$url = "https://xml.websejler.dk/da/baad/1234";
$xml = simplexml_load_file($url);
print_r($xml);
echo $xml[baad][baadNavn];
?>
What do I wrong?
Print_r gives me:
SimpleXMLElement Object ( [baad] => SimpleXMLElement Object ( [#attributes] => Array ( [baadId] => 1234 [maalerId] => 32217 [baadNavn] => Ongo Bongo [baadStatus] => dhkolbaad [dhKlasseStatus] => skrogmedspeciel [nation] => DEN [sejlnummer] => 46 [byggerNavn] => Granada Yacht [byggeAar] => 1978 [maaleDato] => 1991-05-13T00:00:00 [stabgodk] => 0 [skrogMaterialeId] => 1003 [materiale] => GRP [opfolg] => 0 [fysisk] => 1 [baadtypeId] => 146 [rigsejlId] => 28158 [skrogId] => 17214 [specielId] => 79368 ) [certifikat] => SimpleXMLElement Object ( [#attributes] => Array ( [certifikatId] => 1234 [gyldigt] => 0 ) ) [baadtype] => SimpleXMLElement Object ( [#attributes] => Array ( [baadtypeId] => 146 [baadtypeNavn] => GRANADA 31 [baadStatus] => dhkolbaad [dhKlasseStatus] => skrogmedspeciel [dhBeregnes] => 1 [bem] => Granada 311 har samme skrog som Granada 31. De første ca. 35 var med blykøl (KC 0,96) - senere kommer det med jernkøl (KC 1,17) [skrogId] => 17214 [specielId] => 79368 ) ) [rigsejl] => SimpleXMLElement Object ( [#attributes] => Array ( [RigsejlId] => 28158 [E] => 3.27 [P] => 11.14 [HB] => 0.15 [MGM] => 2.10 [MGU] => 1.21 [Tmax] => 12.10 [LP] => 5.23 [FSP] => 0.08 [SPL] => 0.00 [J] => 3.49 [TPS] => 0.00 [JHW] => 0.00 [ISP] => 12.38 [SL] => 0.00 [SLU] => 0.00 [SLE] => 0.00 [SF] => 0.00 [SMG] => 0.00 [SFA] => 0.00 [SMGA] => 0.00 [PropelId] => 2 [propel] => Fri foldepropel med 2-3 blade (2) [RF] => 0 [MF] => 0 [HF] => 0 ) ) [skrog] => SimpleXMLElement Object ( [#attributes] => Array ( [SkrogId] => 17214 [Gmax] => 6.42 [SGmax] => 5.59 [FBSB] => 0.93 [FBBB] => 0.94 [SBmax] => 5.73 [UDFSB] => 0.26 [UDFBB] => 0.26 [OF] => 1.17 [OA] => 0.00 [UDHBmax] => 0.00 [UDHmax] => 0.00 [STF] => 1.11 [AF] => 0.00 ) ) [speciel] => SimpleXMLElement Object ( [#attributes] => Array ( [SpecielId] => 79368 [Bmax] => 3.05 [LOA] => 9.38 [D] => 4.17 [K] => 1.80 [KC] => 0.96 [KFId] => 1 [KF] => Normal [KontrolVejet] => 0 [KontrolMaalt] => 0 [KontrolKrenget] => 0 ) ) [ejer] => SimpleXMLElement Object ( [#attributes] => Array ( [personId] => 53371 [klubId] => 318 [klubNavn] => Aarhus Sejlklub [arrangor] => 1 ) ) [offentligmaaler] => SimpleXMLElement Object ( [#attributes] => Array ( [personId] => 32217 [aktiv] => 0 [maaHentePersonlister] => 0 [offentlig] => 0 [sejlmager] => 0 [maalerbem] => [navn] => Niels Agerskov ) ) [beregning] => SimpleXMLElement Object ( [#attributes] => Array ( [baadId] => 1234 [status] => beregnet [oprettetTid] => 2019-05-10T12:15:32.637 [beregnetTid] => 2019-05-10T12:16:31.447 [beregnetOATid] => 43595.5115 [beskedSendes] => 1 ) ) ) )
XML files contains:
<websejler>
<baad baadId="1234" maalerId="32217" baadNavn="Ongo Bongo" baadStatus="dhkolbaad" dhKlasseStatus="skrogmedspeciel" nation="DEN" sejlnummer="46" byggerNavn="Granada Yacht" byggeAar="1978" maaleDato="1991-05-13T00:00:00" stabgodk="0" skrogMaterialeId="1003" materiale="GRP" opfolg="0" fysisk="1" baadtypeId="146" rigsejlId="28158" skrogId="17214" specielId="79368">
<certifikat certifikatId="1234" gyldigt="0"/>
<baadtype baadtypeId="146" baadtypeNavn="GRANADA 31" baadStatus="dhkolbaad" dhKlasseStatus="skrogmedspeciel" dhBeregnes="1" bem="Granada 311 har samme skrog som Granada 31. De første ca. 35 var med blykøl (KC 0,96) - senere kommer det med jernkøl (KC 1,17)" skrogId="17214" specielId="79368"/>
<rigsejl RigsejlId="28158" E="3.27" P="11.14" HB="0.15" MGM="2.10" MGU="1.21" Tmax="12.10" LP="5.23" FSP="0.08" SPL="0.00" J="3.49" TPS="0.00" JHW="0.00" ISP="12.38" SL="0.00" SLU="0.00" SLE="0.00" SF="0.00" SMG="0.00" SFA="0.00" SMGA="0.00" PropelId="2" propel="Fri foldepropel med 2-3 blade (2)" RF="0" MF="0" HF="0"/>
<skrog SkrogId="17214" Gmax="6.42" SGmax="5.59" FBSB="0.93" FBBB="0.94" SBmax="5.73" UDFSB="0.26" UDFBB="0.26" OF="1.17" OA="0.00" UDHBmax="0.00" UDHmax="0.00" STF="1.11" AF="0.00"/>
<speciel SpecielId="79368" Bmax="3.05" LOA="9.38" D="4.17" K="1.80" KC="0.96" KFId="1" KF="Normal" KontrolVejet="0" KontrolMaalt="0" KontrolKrenget="0"/>
<ejer personId="53371" klubId="318" klubNavn="Aarhus Sejlklub" arrangor="1"/>
<offentligmaaler personId="32217" aktiv="0" maaHentePersonlister="0" offentlig="0" sejlmager="0" maalerbem="" navn="Niels Agerskov"/>
<beregning baadId="1234" status="beregnet" oprettetTid="2019-05-10T12:15:32.637" beregnetTid="2019-05-10T12:16:31.447" beregnetOATid="43595.5115" beskedSendes="1"/>
</baad>
</websejler>
I expect to get "Ongo Bongo" as result.
$url = "https://xml.websejler.dk/da/baad/1234";
$xml = simplexml_load_file($url);
echo (string) $xml->baad->attributes()['baadNavn']; // Ongo Bongo
You can use the attributes() function on the node to get it's attributes:
$xml_str = '<xml>
<node>
<someTag cp="c2">content</someTag>
</node>
</xml>';
$res = simplexml_load_string($xml_str);
$items = $res->xpath("//someTag");
var_dump((string) $items[0]->attributes()->cp);
The returned element is an SimpleXMLElement, so in order to use it I converted it to string (using the (string) cast).

How to split array data returned from json string in php

I have json return string like given below. I want to extract cancellation Policy list of objects like cutoff Time and refund In Percentage. I tried using for-loop but it didn't help me. Can you please help me on extracting this.
Array (
[apiStatus] => Array ( [success] => 1 [message] => SUCCESS ) <br>
[apiAvailableBuses] => Array ( <br>
[0] => Array ( [droppingPoints] => [availableSeats] => 41 <br>[partialCancellationAllowed] => [arrivalTime] => 08:00 AM <br>
[cancellationPolicy] => [<br>
{"cutoffTime":"1","refundInPercentage":"10"},<br>
{"cutoffTime":"2","refundInPercentage":"50"},<br>
{"cutoffTime":"4","refundInPercentage":"90"}<br>
] <br>
[boardingPoints] => Array ( [0] => Array ( [time] => 09:00PM [location] => Ameerpet,|Jeans Corner 9687452130 [id] => 6 ) [1] => Array ( [time] => 09:15PM [location] => S.R Nagar,S.R Nagar [id] => 2224 ) [2] => Array ( [time] => 09:10PM [location] => Kondapur,Toyota Show room [id] => 2244 ) ) [operatorName] => Deepak Travels [departureTime] => 9:00 PM [mTicketAllowed] => [idProofRequired] => [serviceId] => 6622 [fare] => 800 [busType] => 2+1 Hi-Tech Non A/c [routeScheduleId] => 6622 [commPCT] => 0 [operatorId] => 213 [inventoryType] => 0 ) <br>
[1] => Array ( [droppingPoints] => [availableSeats] => 41 [partialCancellationAllowed] => [arrivalTime] => 07:00 AM <br>
[cancellationPolicy] => [<br>
{"cutoffTime":"1","refundInPercentage":"10"},<br>
{"cutoffTime":"2","refundInPercentage":"50"},<br>
{"cutoffTime":"4","refundInPercentage":"90"}<br>
] <br>
[boardingPoints] => Array ( [0] => Array ( [time] => 09:10PM [location] => Ameerpet,|Jeans Corner [id] => 6 ) [1] => Array ( [time] => 09:00PM [location] => S.R Nagar,S.R Nagar [id] => 2224 ) [2] => Array ( [time] => 08:30PM [location] => KUKATPALLY,JNTU [id] => 2230 ) ) [operatorName] => Dhanunjayabus [departureTime] => 9:00 PM [mTicketAllowed] => [idProofRequired] => [serviceId] => 6743 [fare] => 900 [busType] => VOLVO [routeScheduleId] => 6743 [commPCT] => 0 [operatorId] => 233 [inventoryType] => 0 )
)
)
Use a foreach() for it like so:
foreach ($your_response['apiAvailableBuses'] as $el) {
$cancellationPolicy[] = $el['cancellationPolicy'];
}
Try this:
foreach($data['apiStatus']['apiAvailableBuses'] as $item) {
foreach($item['cancellationPolicy'] as $key => $json) {
$jsonDecoded = json_decode($json, true);
// And you will have access to the data like this
// $jsonDecoded['cutoffTime'];
// $jsonDecoded['refundInPercentage'];
}
}
$response = json_decode($apiResponse);
$cancellationPolicies = [];
foreach ($response->apiAvailableBuses as $availableBus) {
$cancellationPolicies[] = $availableBus['cancellationPolicy'];
// if you want to display something you can simply do it like this;
echo $availableBus['cancellationPolicy']->cutoffTime;
}

PHP: How to parse a stdClass Object?

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.

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