PHP Get JSON Values Issue [duplicate] - php

This question already has an answer here:
How to extract and access data from JSON with PHP?
(1 answer)
Closed 6 years ago.
I'm receiving some JSON POST data from a Webhook into my server. I can get the JSON data as follows:
$orderJSON = file_get_contents('php://input');
which returns this JSON:
{
"order": {
"billing_address": {
"address_1": "76 Pacific Drive",
"address_2": "",
"city": "Bondi",
"company": "Hanson Media",
"country": "AU",
"email": "testing#gmail.com",
"first_name": "Hansel",
"last_name": "Gretten",
"phone": "212 554 7855",
"postcode": "2026",
"state": "NSW"
},
"cart_tax": "3.60",
"completed_at": "2016-12-19T11:07:15Z",
"coupon_lines": [],
"created_at": "2016-12-19T11:07:15Z",
"currency": "AUD",
"customer": {
"billing_address": {
"address_1": "76 Pacific Drive",
"address_2": "",
"city": "Bondi",
"company": "Hanson Media",
"country": "AU",
"email": "testing#gmail.com",
"first_name": "Hansel",
"last_name": "Gretten",
"phone": "212 554 7855",
"postcode": "2026",
"state": "NSW"
},
"email": "testing#gmail.com",
"first_name": "Hansel",
"id": 0,
"last_name": "Gretten",
"shipping_address": {
"address_1": "76 Pacific Drive",
"address_2": "",
"city": "Bondi",
"company": "Hanson Media",
"country": "AU",
"first_name": "Hansel",
"last_name": "Gretten",
"postcode": "2026",
"state": "NSW"
}
},
"fee_lines": [],
"id": 3304,
"is_vat_exempt": false,
"line_items": [
{
"id": 113,
"meta": [],
"name": "Happy Ninja",
"price": "18.00",
"product_id": 37,
"quantity": 2,
"sku": "",
"subtotal": "36.00",
"subtotal_tax": "3.60",
"tax_class": null,
"total": "36.00",
"total_tax": "3.60"
},
{
"id": 114,
"meta": [],
"name": "Water Bottles",
"price": "20.50",
"product_id": 3291,
"quantity": 1,
"sku": "PD885536",
"subtotal": "20.50",
"subtotal_tax": "0.00",
"tax_class": "standard",
"total": "20.50",
"total_tax": "0.00"
}
],
"note": "Call to arrange delivery time",
"order_key": "wc_order_5857bf639d951",
"order_number": 3304,
"payment_details": {
"method_id": "eway",
"method_title": "Credit Card",
"paid": false
},
"shipping_address": {
"address_1": "76 Pacific Drive",
"address_2": "",
"city": "Bondi",
"company": "Hanson Media",
"country": "AU",
"first_name": "Hansel",
"last_name": "Gretten",
"postcode": "2026",
"state": "NSW"
},
"shipping_lines": [
{
"id": 115,
"method_id": "local_pickup:1",
"method_title": "Local Pickup",
"total": "0.00"
}
],
"shipping_methods": "Local Pickup",
"shipping_tax": "0.00",
"status": "pending",
"subtotal": "56.50",
"tax_lines": [
{
"code": "AU-GST-1",
"compound": false,
"id": 116,
"rate_id": "1",
"title": "GST",
"total": "3.60"
}
],
"total": "60.10",
"total_discount": "0.00",
"total_line_items_quantity": 3,
"total_shipping": "0.00",
"total_tax": "3.60",
"updated_at": "2016-12-19T11:07:15Z",
"view_order_url": "https://mywebsite.com/my-account/view-order/3304"
}
}
I now need to get individual elements from the JSON, e.g. I would like to get the id value (3304). I've tried:
$orderID = $orderJSON->id;
and
$orderID = $orderJSON[id];
but this just generates errors like 'Trying to get property of non-object'.

Use the json_decode() function to translate your JSON file into a PHP readable data.
<?php
$json = json_decode($orderJSON);
Once you get your JSON file decoded, you can use the function print_r() to print a nice representation of your datas.
<?php
print_r($orderJSON);
This can help you identify how the file is formed and thus determine all the dimensions you need to display the wanted value.
JSON to nice
Now, if you look closely, you'll see that in order to print your ID, you need to pass through the order dimension.
So you may want to use the syntax $json->order->id to target the wanted ID.
<?php
echo $json->order->id;
Display the ID from JSON
PHP : JSON.
PHP : print_r().

You need to use json_decode() first as I can't see this in your question.
id is under order parent so you need to do sonething like $orderJSON->order->id
You must also check decoded $orderJSON is not empty
Example
$orderJSON = json_decode($orderJSON);
if (empty($orderJSON)) {
throw new RuntimeException('Malformed json');
}
$orderID = $orderJSON->order->id;

Related

creating invoice is not working through Paypal REST API

I am facing the problem to create the PayPal invoice through the REST API. I got the access token by using auth API of https://api.sandbox.paypal.com/v1/oauth2/token. I am passing the token in the HEADER to create an invoice in the create invoice API of https://api.sandbox.paypal.com/v1/invoicing/invoices/.
Header:
Below is my JSON body.
{
"merchant_info": {
"email": "krpdas-facilitator#gmail.com",
"first_name": "prabhu",
"last_name": "kr",
"business_name": "prabhu kr",
"phone": {
"country_code": "91",
"national_number": "2222233333"
},
"address": {
"line1": "xxxxxxxxxxx,xxxxxxx",
"city": "xxxxxxx",
"state": "xxxxxx",
"postal_code": "888888",
"country_code": "IN"
}
},
"billing_info": [
{
"email": "lalith-facilitator#abacies.com",
"business_name": "test facilitator",
"additional_info": "test facilitator's Test Store",
"address": {
"line1": "1 Main St",
"city": "San Jose",
"state": "CA",
"postal_code": "95131",
"country_code": "US"
}
}
],
"shipping_info": {
"first_name": "Lalith",
"last_name": "Kumar",
"address": {
"line1": "1234 Main Street",
"city": "Anytown",
"state": "CA",
"postal_code": "98765",
"country_code": "US"
}
},
"items": [
{
"name": "Zoom System wireless headphones",
"quantity": 2,
"unit_price": {
"currency": "USD",
"value": "120"
},
"tax": {
"name": "Tax",
"percent": 8
}
},
{
"name": "Bluetooth speaker",
"quantity": 1,
"unit_price": {
"currency": "USD",
"value": "145"
},
"tax": {
"name": "Tax",
"percent": 8
}
}
],
"discount": {
"percent": 1
},
"shipping_cost": {
"amount": {
"currency": "USD",
"value": "10"
}
},
"note": "Thank you for your business.",
"terms": "No refunds after 30 days."
}
I tried with changing the access token and merchant email ids. But always I am getting the same error as 401 unauthorized. I am following the documentation of https://developer.paypal.com/docs/api/invoicing/.
ERROR:
{
"name": "AUTHORIZATION_ERROR",
"message": "Authorization error occurred.",
"information_link": "https://developer.paypal.com/docs/api/invoicing/#errors",
"debug_id": "f89a30f937ced"
}
Scope:
"scope": "https://api.paypal.com/v1/payments/.*
https://uri.paypal.com/services/payments/refund
https://uri.paypal.com/services/applications/webhooks
https://uri.paypal.com/services/payments/payment/authcapture
https://uri.paypal.com/payments/payouts https://api.paypal.com/v1/vault/credit-card/.*
https://uri.paypal.com/services/disputes/read-seller
https://uri.paypal.com/services/subscriptions
https://uri.paypal.com/services/disputes/read-buyer
https://api.paypal.com/v1/vault/credit-card openid
https://uri.paypal.com/services/disputes/update-seller
https://uri.paypal.com/services/payments/realtimepayment",

I want to insert item meta in in order through rest API in WooCommerce

I created one text field through WC Field Factory with the name of "Camper Name"
Showing in this product
Now the problem is when I'm filling this field from frontend and placing order this field show in Woocommerce Order API when I'm retrieving data but when I'm trying to insert meta through creating Order API then not going in order and when I'm retrieving order show "meta"[] empty. Can anyone help to resolve this issue?
Here I'm try to create order through POSTMAN
{
"payment_method": "cod",
"payment_method_title": "Direct Bank Transfer",
"set_paid": true,
"billing": {
"first_name": "Ram",
"last_name": "Kumar",
"address_1": "969 Market",
"address_2": "",
"city": "Vsp",
"state": "AP",
"postcode": "530016",
"country": "India",
"email": "ramkumar#example.com",
"phone": "(986) 444-5555"
},
"shipping": {
"first_name": "Ram",
"last_name": "Kumar",
"address_1": "969 Market",
"address_2": "",
"city": "Vsp",
"state": "AP",
"postcode": "530016",
"country": "India"
},
"line_items": [
{
"product_id": 938,
"quantity": 1,
"meta": [
{
"key": "Camper Name",
"label":"Camper Name",
"value":"furqan fazlani"
}
]
},
{
"product_id": 262,
"quantity": 5
}
],
"shipping_lines": [
{
"method_id": "flat_rate",
"method_title": "Flat Rate",
"total": 2
}
]
}

Get the values in PHP of three objects in Tripadvisor JSON API file

Been struggling with this for too long now, so am kindly asking for your help.
How can I, using PHP, get the values of the text fields in the reviews of which there are three in this JSON file below.
Want to use a foreach loop for this, thanks for helping me out!
{
"address_obj": {
"street1": "Rustenburgerstreet 384",
"street2": null,
"city": "Amsterdam",
"state": "North Holland Province",
"country": "The Netherlands",
"postalcode": "1072 HG",
"address_string": "Rustenburgerstreet 384, 1072 HG Amsterdam The Netherlands"
},
"percent_recommended": null,
"latitude": "52.35162",
"rating": "5.0",
"attraction_types": [
{
"name": "concerts",
"localized_name": "Concerts"
},
{
"name": "blues bars",
"localized_name": "Blues Bars"
},
{
"name": "jazz bars",
"localized_name": "Jazz Bars"
},
{
"name": "bar/ clubs",
"localized_name": "Bars & Clubs"
}
],
"wikipedia_info": null,
"location_id": "3724036",
"review_rating_count": {
"1": "0",
"2": "0",
"3": "1",
"4": "4",
"5": "35"
},
"ranking_data": {
"ranking_string": "#12 of 73 Theater & Concerts in Amsterdam",
"ranking_out_of": "73",
"geo_location_id": "188590",
"ranking": "12",
"geo_location_name": "Amsterdam"
},
"photo_count": "35",
"location_string": "Amsterdam, North Holland Province",
"trip_types": [
{
"name": "business",
"value": "0",
"localized_name": "Business"
},
{
"name": "couples",
"value": "8",
"localized_name": "Couples"
},
{
"name": "solo",
"value": "7",
"localized_name": "Solo travel"
},
{
"name": "family",
"value": "0",
"localized_name": "Family"
},
{
"name": "friends",
"value": "21",
"localized_name": "Friends getaway"
}
],
"web_url": "Attraction_Review-g188590-d3724036-Reviews-m34757-CC_Music_Cafe-Amsterdam_North_Holland_Province.html",
"reviews": [
{
"id": "353301385",
"lang": "en",
"location_id": "3724036",
"published_date": "2016-03-06T05:20:19-0500",
"rating": 5,
"helpful_votes": "0",
"rating_image_url": "img/cdsi/img2/ratings/traveler/s5.0-34757-5.png",
"url": "ShowUserReviews-g188590-d3724036-r353301385-CC_Music_Cafe-Amsterdam_North_Holland_Province.html#review353301385",
"trip_type": "Solo travel",
"travel_date": "2016-02",
"text": "I am a regular visitor of CC Muziekcafé Amsterdam but have felt at home from the very first time. What I like about CC is the atmosphere where great music and hospitality are mixed in the best way...",
"user": {
"username": "Yvon H",
"user_location": {
"name": "Groningen Province, The Netherlands",
"id": "188570"
}
},
"title": "A great place to hear live music and meet all sorts of interesting people, both local and traveling",
"is_machine_translated": false
},
{
"id": "351658487",
"lang": "en",
"location_id": "3724036",
"published_date": "2016-02-28T11:13:12-0500",
"rating": 5,
"helpful_votes": "0",
"rating_image_url": "img/cdsi/img2/ratings/traveler/s5.0-34757-5.png",
"url": "ShowUserReviews-g188590-d3724036-r351658487-CC_Music_Cafe-Amsterdam_North_Holland_Province.html#review351658487",
"trip_type": "Friends getaway",
"travel_date": "2016-02",
"text": "4th time we have been here, another great night at the music cafe, friendly people and a barman who knows how to just put enough swear words in to sound cool",
"user": {
"username": "Francois S",
"user_location": {
"name": "Cardiff, United Kingdom",
"id": "186460"
}
},
"title": "Jazz funk Jam session night Thursday",
"is_machine_translated": false
},
{
"id": "350605184",
"lang": "en",
"location_id": "3724036",
"published_date": "2016-02-24T10:18:57-0500",
"rating": 5,
"helpful_votes": "1",
"rating_image_url": "img/cdsi/img2/ratings/traveler/s5.0-34757-5.png",
"url": "ShowUserReviews-g188590-d3724036-r350605184-CC_Music_Cafe-Amsterdam_North_Holland_Province.html#review350605184",
"trip_type": "Couples",
"travel_date": "2015-09",
"text": "CC muziekcafe is a very cosy place with excellent live music and interaction with the musicians. What really makes the place is the owner Rene who knows a lot about music and now and then even sings...",
"user": {
"username": "ImagineNL",
"user_location": {
"name": "Schagen, The Netherlands",
"id": "609049"
}
},
"title": "Cupid",
"is_machine_translated": false
}
],
You can use this code
<?php
$json = <<<EOF
{
"address_obj": {
"street1": "Rustenburgerstreet 384",
"street2": null,
"city": "Amsterdam",
"state": "North Holland Province",
"country": "The Netherlands",
"postalcode": "1072 HG",
"address_string": "Rustenburgerstreet 384, 1072 HG Amsterdam The Netherlands"
},
"percent_recommended": null,
"latitude": "52.35162",
"rating": "5.0",
"attraction_types": [
{
"name": "concerts",
"localized_name": "Concerts"
},
{
"name": "blues bars",
"localized_name": "Blues Bars"
},
{
"name": "jazz bars",
"localized_name": "Jazz Bars"
},
{
"name": "bar/ clubs",
"localized_name": "Bars & Clubs"
}
],
"wikipedia_info": null,
"location_id": "3724036",
"review_rating_count": {
"1": "0",
"2": "0",
"3": "1",
"4": "4",
"5": "35"
},
"ranking_data": {
"ranking_string": "#12 of 73 Theater & Concerts in Amsterdam",
"ranking_out_of": "73",
"geo_location_id": "188590",
"ranking": "12",
"geo_location_name": "Amsterdam"
},
"photo_count": "35",
"location_string": "Amsterdam, North Holland Province",
"trip_types": [
{
"name": "business",
"value": "0",
"localized_name": "Business"
},
{
"name": "couples",
"value": "8",
"localized_name": "Couples"
},
{
"name": "solo",
"value": "7",
"localized_name": "Solo travel"
},
{
"name": "family",
"value": "0",
"localized_name": "Family"
},
{
"name": "friends",
"value": "21",
"localized_name": "Friends getaway"
}
],
"web_url": "Attraction_Review-g188590-d3724036-Reviews-m34757-CC_Music_Cafe-Amsterdam_North_Holland_Province.html",
"reviews": [
{
"id": "353301385",
"lang": "en",
"location_id": "3724036",
"published_date": "2016-03-06T05:20:19-0500",
"rating": 5,
"helpful_votes": "0",
"rating_image_url": "img/cdsi/img2/ratings/traveler/s5.0-34757-5.png",
"url": "ShowUserReviews-g188590-d3724036-r353301385-CC_Music_Cafe-Amsterdam_North_Holland_Province.html#review353301385",
"trip_type": "Solo travel",
"travel_date": "2016-02",
"text": "I am a regular visitor of CC Muziekcafé Amsterdam but have felt at home from the very first time. What I like about CC is the atmosphere where great music and hospitality are mixed in the best way...",
"user": {
"username": "Yvon H",
"user_location": {
"name": "Groningen Province, The Netherlands",
"id": "188570"
}
},
"title": "A great place to hear live music and meet all sorts of interesting people, both local and traveling",
"is_machine_translated": false
},
{
"id": "351658487",
"lang": "en",
"location_id": "3724036",
"published_date": "2016-02-28T11:13:12-0500",
"rating": 5,
"helpful_votes": "0",
"rating_image_url": "img/cdsi/img2/ratings/traveler/s5.0-34757-5.png",
"url": "ShowUserReviews-g188590-d3724036-r351658487-CC_Music_Cafe-Amsterdam_North_Holland_Province.html#review351658487",
"trip_type": "Friends getaway",
"travel_date": "2016-02",
"text": "4th time we have been here, another great night at the music cafe, friendly people and a barman who knows how to just put enough swear words in to sound cool",
"user": {
"username": "Francois S",
"user_location": {
"name": "Cardiff, United Kingdom",
"id": "186460"
}
},
"title": "Jazz funk Jam session night Thursday",
"is_machine_translated": false
},
{
"id": "350605184",
"lang": "en",
"location_id": "3724036",
"published_date": "2016-02-24T10:18:57-0500",
"rating": 5,
"helpful_votes": "1",
"rating_image_url": "img/cdsi/img2/ratings/traveler/s5.0-34757-5.png",
"url": "ShowUserReviews-g188590-d3724036-r350605184-CC_Music_Cafe-Amsterdam_North_Holland_Province.html#review350605184",
"trip_type": "Couples",
"travel_date": "2015-09",
"text": "CC muziekcafe is a very cosy place with excellent live music and interaction with the musicians. What really makes the place is the owner Rene who knows a lot about music and now and then even sings...",
"user": {
"username": "ImagineNL",
"user_location": {
"name": "Schagen, The Netherlands",
"id": "609049"
}
},
"title": "Cupid",
"is_machine_translated": false
}
]
}
EOF;
$array = json_decode($json, true);
$texts = array_map(
function($item) {
return $item['text'];
}, $array['reviews']
);
It doesn't seem like you need a foreach to fetch the reviews element. Not sure if I understood your question correct, but did you want something like this:
$assoc_json = json_decode($your_json, true);
var_dump($assoc_json['reviews']);
The above turns your json into an associative array, and just access the review element.
A simple, naive approach would be:
//Loads your json file 'tripadvisor' into jsonString
$jsonString = file_get_contents("/tripadvisor.json");
//Turns your string into an associative array
$tripJsonAssoc = json_decode($jsonString, true);
//Iterate through each review and store it in result
$result = array();
foreach($tripJsonAssoc['reviews'] as $review) {
$result[] = array('text' => $review['text'],
'rating' => $review['rating']);
}
//Do what you need to do with result
//...
Or you can just do your own stuff inside the foreach loop.
This answer gives you another way (more elegant) to create the 'result' array, but since you asked for a 'foreach', I thought I would add my 5 cents.

Parsing Rome2Rio json file with PHP

I am trying to extract a segment from the json file of Rome2Rio API with PHP but I cant get an output.
The json file from rome2rio:
{
"serveTime": 1,
"places": [
{ "kind": "town", "name": "Kozani", "longName": "Kozani, Greece", "pos": "40.29892,21.7972", "countryCode": "GR", "regionCode": "ESYE13" },
{ "kind": "city", "name": "Thessaloniki", "longName": "Thessaloniki, Greece", "pos": "40.64032,22.93527", "countryCode": "GR", "regionCode": "ESYE12" }
],
"airports": [],
"airlines": [],
"aircrafts": [],
"agencies": [{
"code": "KTEL",
"name": "KTEL",
"url": "http://www.ktelbus.com/?module=default\u0026pages_id=15\u0026lang=en",
"iconPath": "/logos/Trains/KTELgr.png",
"iconSize": "27,23",
"iconOffset": "0,0"
}
],
"routes": [
{ "name": "Bus", "distance": 121.04, "duration": 120, "totalTransferDuration": 0, "indicativePrice": { "price": 9, "currency": "EUR", "isFreeTransfer": 0 },
"stops": [
{ "name": "Kozani", "pos": "40.30032,21.79763", "kind": "station", "countryCode": "GR", "timeZone": "Europe/Athens" },
{ "name": "Thessaloniki", "pos": "40.6545,22.90233", "kind": "station", "countryCode": "GR", "timeZone": "Europe/Athens" }
]
The PHP code I wrote is:
$json_rome2rio = file_get_contents("http://free.rome2rio.com/api/1.2/json/Search?key=&oName=kozani&dName=thessaloniki");
$parsed_json_r = json_decode($json_rome2rio);
echo $parsed_json_r->agencies->name;
The agencies property contains an array of agencies (note the square brackets). To access the name as you're after, you can do the following:
echo $parsed_json_r->agencies[0]->name;
This assumes that at least one agency is returned and that the agency you are after is the first one if more than one is returned.

Extracting values from JSON data

I have the JSON data given below. The 'crop' array contains multiple array of crop price, I want to get average crop price of all districts(using 'district_id').
<i>{
"status": "ok",
"count": 7,
"crop": [
{
"id": "133",
"crop_id": "81",
"price": "45.00",
"description": null,
"user_id": "27",
"block_id": "1",
"longitude": "87.8661808",
"latitude": "23.2340073",
"date": "2014-02-03",
"time": "12:44:43",
"district_id": "1"
},
{
"id": "135",
"crop_id": "81",
"price": "10.50",
"description": null,
"user_id": "27",
"block_id": "1",
"longitude": "87.8662402",
"latitude": "23.2339822",
"date": "2014-02-03",
"time": "12:44:54",
"district_id": "1"
},
{
"id": "143",
"crop_id": "81",
"price": "35",
"description": null,
"user_id": "27",
"block_id": "1",
"longitude": "0.0",
"latitude": "0.0",
"date": "2014-02-03",
"time": "13:12:50",
"district_id": "1"
},
{
"id": "146",
"crop_id": "81",
"price": "85",
"description": null,
"user_id": "27",
"block_id": "1",
"longitude": "0.0",
"latitude": "0.0",
"date": "2014-02-03",
"time": "14:29:07",
"district_id": "1"
},
{
"id": "148",
"crop_id": "81",
"price": "25",
"description": null,
"user_id": "27",
"block_id": "1",
"longitude": "0.0",
"latitude": "0.0",
"date": "2014-02-03",
"time": "14:58:01",
"district_id": "1"
},
{
"id": "132",
"crop_id": "81",
"price": "10",
"description": null,
"user_id": "119",
"block_id": "34",
"longitude": "0.0",
"latitude": "0.0",
"date": "2014-02-03",
"time": "12:41:49",
"district_id": "4"
},
{
"id": "134",
"crop_id": "81",
"price": "12",
"description": null,
"user_id": "119",
"block_id": "34",
"longitude": "0.0",
"latitude": "0.0",
"date": "2014-02-03",
"time": "12:43:50",
"district_id": "4"
}
]
}</i>
Use json_decode method to convert it to an std_class or use the 2nd parameter of this method to convert it to an associated array.
Take a look at http://in1.php.net/json_decode
Once you decode it, you can easily access the variables like accessing properties of a class or as an array object if you are converting to an associated array
First you have too decode the JSON using json_decode function, then access using variables.
Do like this..
//Assign your JSON data to this $json variable as shown in the demo.
$arr = json_decode($json,1);
foreach($arr['crop'] as $arr1)
{
foreach($arr1 as $k=>$v)
{
if($arr1['district_id']==1)
{
$avgpr[] = $arr1['price'];
}
}
}
echo $avgprice = array_sum($avgpr)/count($avgpr);
OUTPUT :
40.1
Demo

Categories