Below is json response and I have problems getting shipping_address data.
{
"orders": [{
"created_at": "2015-01-04T02:20:03+01:00",
"financial_status": "paid",
"id": 384536708,
"total_price": "45.00",
"line_items": [{
"fulfillment_service": "manual",
"fulfillment_status": null,
"gift_card": false,
"grams": 0,
"price": "45.00",
"quantity": 1,
"requires_shipping": true,
"taxable": true,
"title": "test",
"vendor": "test",
"name": "test",
"properties": [],
"product_exists": true,
"fulfillable_quantity": 1,
"tax_lines": []
}],
"shipping_address": {
"address1": "Street 20",
"address2": "",
"city": "City",
"company": "",
"country": "USA",
"first_name": "Name",
"last_name": "Surname",
"latitude": 45.000000,
"longitude": 10.000000,
"phone": "",
"province": "",
"zip": "12345",
"name": "Name Surname",
"country_code": "US",
"province_code": null
}
}, [...]
I can get orders with this code:
$content = file_get_contents($url);
$json = json_decode($content, true);
foreach($json['orders'] as $order){
echo "<td>".$order['id']."</td>";
}
But when I try to get shipping_address data like this:
foreach ($json['shipping_address'] as $sa) {
echo "<td>".$sa['name']."</td>";
}
Then i get: Notice: Undefined index: shipping_address and Warning: Invalid argument supplied for foreach()
Am I targeting array wrong?
It should be -
foreach ($json['orders']['shipping_address'] as $sa) {
Try this -
foreach($json['orders'] as $order){
echo "<td>".$order['id']."</td>";
echo "<td>".$order['shipping_address']['name']."</td>";
}
foreach ($json['orders']['shipping_address'] as $sa) {
echo "<td>".$sa['name']."</td>";
}
Try this :
$content = file_get_contents($url);
$json = json_decode($content, true);
foreach($json as $orders){
foreach($orders as $odarr){
foreach($odarr['shipping_address'] as $shipadd){
echo $shipadd['address1'];
}
}
}
Related
Here is the code using which i am getting data:
<?php
header('Content-Type: text/html; charset=UTF-8');
$request = file_get_contents('php://input');
//$req_dump = print_r( $request, true );
$fp = file_put_contents( 'request.log', urldecode(json_encode($request)));
?>
output :
domain_prefix = test & payload = {
"attributed_cost": "0.00",
"count": 50,
"id": "da674e25-5d9c-a8e2-1d5e-aa018b6cc1c3",
"outlet": {
"id": "3faf0608-91fa-11e3-a0f5-b8ca3a64f8f4",
"name": "West End Shop",
"tax_id": "e52b2846-e920-11e5-f98b-29c175501027",
"time_zone": "Australia/Brisbane"
},
"outlet_id": "3faf0608-91fa-11e3-a0f5-b8ca3a64f8f4",
"product": {
"active": true,
"attributed_cost": null,
"base_name": "Test Productss",
"button_order": null,
"categories": [],
"deleted_at": null,
"description": "",
"handle": "testproducts",
"id": "bfe919c4-6357-46c9-a333-d1db636446c5",
"name": "Test Productss",
"sku": "10203",
"source": "USER",
"source_id": null,
"source_variant_id": null,
"supply_price": "0.00",
"taxes": [{
"outlet_id": "3faf0608-91fa-11e3-a0f5-b8ca3a64f8f4",
"tax_id": "e52b2846-e920-11e5-f98b-29c175501027"
}],
"variant_options": [],
"variant_parent_id": null
},
"product_id": "bfe919c4-6357-46c9-a333-d1db636446c5",
"reorder_point": "0",
"restock_level": "0",
"version": 16073287694
} & retailer_id = 3 fa8309c - 91 fa - 11e3 - a0f5 - b8ca3a64f8f4 & type = inventory.update
I am not sure how to fetch "count" & "id" & "product_id" attributes value from this.
I have tried parse_str but it didn't work.
let me know your thoughts on this, how to fetch data from it ?
Thankyou
if your $request is like that output then you can try
you can try
parse_str($request, $parse_request);
$payload = json_decode($parse_request["payload"], true);
$id = $payload["id"];
$count = $payload["count"];
$product_id = $payload["product"]["id"];
I'm very new to the world of APIs and am currently trying to display all reviews I have on my reviews.io account for a specific product. I've tried to make the following script, which now seems to work, however, I would love to have the results sorted nicely in a for-each loop.
Here my current script:
<?php
$header_data = array(
'store' => 'MYSHOP',
'apikey' => 'MYKEY',
'method' => 'GET'
);
$ch = curl_init();
$curlOpts = array(
CURLOPT_URL => 'https://api.reviews.co.uk/product/review?store=MYSHOP&sku=TSCB20&apikey=MYKEY',
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_HEADER => false
);
curl_setopt_array($ch, $curlOpts);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Length: 0'));
$rv = curl_exec($ch);
$data = json_decode($rv,true);
curl_close($ch);
?>
This outputs all reviews in Raw code or JSON I believe, however, I would like to have them displayed nicely in a div for each item.
The output is as follows (formatted):
{
"store": {
"name": "",
"logo": ""
},
"stats": {
"average": "5.0000",
"count": 2
},
"reviews": {
"total": 2,
"per_page": 15,
"current_page": 1,
"last_page": 1,
"from": 1,
"to": 2,
"data": [
{
"votes": null,
"flags": null,
"title": "David",
"product_review_id": 2978412,
"review": "...is beautiful and I had a great time on this tour. Already started to plan my next trip with them",
"sku": "TSCB20",
"rating": 5,
"date_created": "",
"order_id": "",
"timeago": "",
"reviewer": {
"first_name": "David",
"last_name": "",
"verified_buyer": "yes",
"address": "",
"profile_picture": "",
"gravatar": "38677a4e8a55189055d6e5bf2efa9ade"
},
"ratings": [],
"replies": [],
"images": [],
"product": {
"sku": "TSCB20",
"name": "",
"description": "",
"link": "",
"image_url": "",
"mpn": "",
"brand": null,
"category": null,
"custom": null
},
"author": {
"email": "david#"
}
},
{
"votes": null,
"flags": null,
"title": null,
"product_review_id": 2978009,
"review": "Exceeded expectations on all fronts cultural and Food ",
"sku": "TSCB20",
"rating": 5,
"date_created": "",
"order_id": "RGFY4ZG",
"timeago": "",
"reviewer": {
"first_name": "Alan",
"last_name": "",
"verified_buyer": "yes",
"address": "",
"profile_picture": "",
"gravatar": "64e2ac644a158b76a82f9e1c5c2886f5"
},
"ratings": [],
"replies": [],
"images": [],
"product": {
"sku": "TSCB20",
"name": "",
"description": "",
"link": "",
"image_url": "",
"mpn": "",
"brand": null,
"category": null,
"custom": null
},
"author": {
"email": ""
}
}
]
},
"ratings": [],
"settings": {
"write_review_button": 1,
"disable_product_seo_css": 0,
"show_product_review_titles": 0
},
"word": "Excellent",
"products": [
{
"sku": "TSCB20",
"name": ""
}
],
"write_review_link": ""
}
My ideal outcome now would be a loop, that fetches the reviewer's name, the review itself and the star-rating. e.g.
<p class="review">Review here</p>
<p class="reviewer">Name here</p>
<p class="rating">Rating here</p>
So technically based on the current output, I should have 2 reviews. Some expert help would be greatly appreciated as I am very new to APIs. Thank you very much in advance.
Simple foreach() will do the job:
<?php foreach($data['reviews']['data'] as $dat){?>
<p class="review"><?php echo $dat['review'];?></p>
<p class="reviewer"><?php echo trim($dat['reviewer']['first_name'].' '.$dat['reviewer']['last_name']);?></p>
<p class="rating"><?php echo $dat['rating'];?></p>
<?php }?>
I am accessing API for "ConnectWise". the data comes into JSON format. i was able to parse the data into table via PHP. however, empty fields in JSON results in Undefined index. This happens for some items with no website, or address for example. the rest shows up fine.
Any help or input would be appreciated.
Here is my code to get the data from Connectwise:
function get_companies(){
$curl = curl_init();
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 1);
curl_setopt($curl, CURLOPT_URL, "https://api-
na.myconnectwise.net/v4_6_release/apis/3.0/company/companies");
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1 );
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
"Authorization: Basic (OUR KEY)",
'Content-type: application/json'
));
$result = curl_exec($curl);
curl_close($curl);
$decoded = json_decode($result,true);
return $decoded;
}
And to display the data:
function list_all_accounts(){
$accounts = get_companies();
if ( !empty ($accounts)){
foreach ($accounts as $account) {
{
echo "
</td>
<td>
$account[id]
</td>
<td>
$account[name]
</td>
<td>
$account[addressLine1]
</td>
<td>
$account[phoneNumber]
</td>
<td>
$account[website]
</td>
<td>
$account[name]
</td>
</tr>";
}
}
}
}
Update - Json Sample
[
{
"id": 250,
"identifier": "company name ",
"name": "company name",
"status": {
"id": 1,
"name": "Active",
"_info": {
"status_href": "https://api-na.myconnectwise.net/v4_6_release/apis/3.0/company/companies/statuses/1"
}
},
"type": {
"id": 1,
"name": "Client",
"_info": {
"type_href": "https://api-na.myconnectwise.net/v4_6_release/apis/3.0/company/companies/types/1"
}
},
"addressLine1": "address line 1",
"city": "New York",
"state": "NY",
"zip": "11111",
"country": {
"id": 1,
"name": "United States",
"_info": {
"country_href": "https://api-na.myconnectwise.net/v4_6_release/apis/3.0/company/countries/1"
}
},
"phoneNumber": "123456789",
"faxNumber": "",
"website": "www.site.com",
"territoryId": 2,
"accountNumber": "",
"dateAcquired": "2006-06-21T04:00:00Z",
"sicCode": {
"id": 1209,
"name": "consulting"
},
"annualRevenue": 0,
"timeZone": {
"id": 1,
"name": "GMT-5/Eastern Time: US & Canada",
"_info": {
"timeZoneSetup_href": "https://api-na.myconnectwise.net/v4_6_release/apis/3.0/system/timeZoneSetups/1"
}
},
"leadFlag": false,
"unsubscribeFlag": false,
"userDefinedField5": "1",
"taxCode": {
"id": 8,
"name": "Tax-State",
"_info": {
"taxCode_href": "https://api-na.myconnectwise.net/v4_6_release/apis/3.0/finance/taxCodes/8"
}
},
"billingTerms": {
"id": 1,
"name": "Net 30 days"
},
"billToCompany": {
"id": 250,
"identifier": "comp1 ",
"name": "company1.",
"_info": {
"company_href": "https://api-na.myconnectwise.net/v4_6_release/apis/3.0/company/companies/250"
}
},
"billingSite": {
"id": 1291,
"name": "company1",
"_info": {
"site_href": "https://api-na.myconnectwise.net/v4_6_release/apis/3.0/company/companies"
}
},
"invoiceDeliveryMethod": {
"id": 1,
"name": "Mail"
},
"deletedFlag": false,
"mobileGuid": "1df91371-6d7a-4778-ab81-f3e7761f5211",
"currency": {
"id": 7,
"symbol": "$",
"isoCode": "USD",
"name": "US Dollars",
"_info": {
"currency_href": "https://api-na.myconnectwise.net/v4_6_release/apis/3.0/finance/currencies/7"
}
},
"_info": {
"lastUpdated": "2018-04-02T16:36:05Z",
"updatedBy": "user1",
"dateEntered": "2006-06-21T16:04:59Z",
}
},
{
"id": 250,
"identifier": "company name ",
"name": "company name",
"status": {
"id": 1,
"name": "Active",
"_info": {
"status_href": "https://api-na.myconnectwise.net/v4_6_release/apis/3.0/company/companies/statuses/1"
}
},
"type": {
"id": 1,
"name": "Client",
"_info": {
"type_href": "https://api-na.myconnectwise.net/v4_6_release/apis/3.0/company/companies/types/1"
}
},
"addressLine1": "address line 1",
"city": "New York",
"state": "NY",
"zip": "11111",
"country": {
"id": 1,
"name": "United States",
"_info": {
"country_href": "https://api-na.myconnectwise.net/v4_6_release/apis/3.0/company/countries/1"
}
},
"phoneNumber": "123456789",
"faxNumber": "",
"website": "www.site.com",
"territoryId": 2,
"accountNumber": "",
"dateAcquired": "2006-06-21T04:00:00Z",
"sicCode": {
"id": 1209,
"name": "consulting"
},
"annualRevenue": 0,
"timeZone": {
"id": 1,
"name": "GMT-5/Eastern Time: US & Canada",
"_info": {
"timeZoneSetup_href": "https://api-na.myconnectwise.net/v4_6_release/apis/3.0/system/timeZoneSetups/1"
}
},
"leadFlag": false,
"unsubscribeFlag": false,
"userDefinedField5": "1",
"taxCode": {
"id": 8,
"name": "Tax-State",
"_info": {
"taxCode_href": "https://api-na.myconnectwise.net/v4_6_release/apis/3.0/finance/taxCodes/8"
}
},
"billingTerms": {
"id": 1,
"name": "Net 30 days"
},
"billToCompany": {
"id": 250,
"identifier": "comp1 ",
"name": "company1.",
"_info": {
"company_href": "https://api-na.myconnectwise.net/v4_6_release/apis/3.0/company/companies/250"
}
},
"billingSite": {
"id": 1291,
"name": "company1",
"_info": {
"site_href": "https://api-na.myconnectwise.net/v4_6_release/apis/3.0/company/companies"
}
},
"invoiceDeliveryMethod": {
"id": 1,
"name": "Mail"
},
"deletedFlag": false,
"mobileGuid": "1df91dd371-6d7addd-4778s-ab81-f3e7761f5211",
"currency": {
"id": 7,
"symbol": "$",
"isoCode": "USD",
"name": "US Dollars",
"_info": {
"currency_href": "https://api-na.myconnectwise.net/v4_6_release/apis/3.0/finance/currencies/7"
}
},
"_info": {
"lastUpdated": "2018-04-02T16:36:05Z",
"updatedBy": "user1",
"dateEntered": "2006-06-21T16:04:59Z",
"enteredBy": "CONVERSION",
}
}
]
json_decode() and https://jsonlint.com/ both complain about the comma after the value on lines 95 and 194. Removing them makes it valid json, after which your code works as soon as you remember to quote the key values for the associative array.
I removed the two offending commas in the json and saved as a file, then added the quoting for your key values on the array, and finally removed the HTML table stuff and such (I'm just running it on command line to see output). Should be easy to put back in...
<?php
function get_companies() {
$j = file_get_contents("json.json");
$jd = json_decode($j, true);
return $jd;
}
$accounts = get_companies();
if (!empty($accounts)) {
foreach ($accounts as $account) {
echo "\n".$account['id'] . "
" . $account['name'] . "
" . $account['addressLine1'] . "
" . $account['phoneNumber'] . "
" . $account['website'] . "
" . $account['name']."\n\n";
}
}
?>
According to your comment, it is possible that some properties that you use in your HTML are not part of the JSON you receive. This means you are accessing an array index that is not set, e.g. with $account[website].
I see two solutions for this:
Only output the data if it is set in the array:
echo '<td>'.(isset($account['website']) ? $account['website'] : '').'</td>';
Use a an array with defaults for all the values as base for your $account array and merge them:
$base = [
'website' => 'no website',
'phoneNumber' => '',
];
foreach ($accounts as $account) {
// this will override all elements of $base with them of $account,
// but only if they are present in $account
$account = array_merge($base, $account);
// ... your output here ...
}
Here is my scenario, for example i have 4000 contacts (return 271257 lines after json_encode) in database, i have called
echo json_encode($response);
But it takes 35-40 second to return response as JSON. So my question is, are there any another options for decrease converting process to json. So i can make fast application.
I have tried a lot by calling below functions
1) json_encode($response, JSON_UNESCAPED_UNICODE);
2)
header('Content-Type: application/json')
echo json_encode($response);
3)
header('Content-Type: application/json')
echo json_encode($response); die;
This is the sample data of single contact
{
"address": {
"primary": {
"id": "",
"address1": "",
"address2": "",
"city": "",
"state": "",
"zipcode": "",
"country": "",
"primary-address": ""
},
"secondary": {
"id": "",
"address1": "",
"address2": "",
"city": "",
"state": "",
"zipcode": "",
"country": "",
"secondary-address": ""
}
},
"groups": [],
"regions": [],
"links": [],
"phone": [
{
"type_id": 2,
"phone_type": "Mobile",
"country_code": "us",
"value": "+1 1830593231",
"is_primary": 1,
"country_code_value": "+1"
}
],
"social": [],
"email": [
{
"type_id": 2,
"type": "Work",
"value": "cron_4000#gmail.com",
"is_primary": 1
}
],
"tags": [],
"action": {
"is_favourite": 0,
"is_following": 0,
"is_stay": 0,
"kit_expired": 0
},
"access": [],
"activity_count": [],
"contact_id": 5768,
"type": 0,
"salutation_id": 1,
"assigned_to": 1,
"first_name": "Cron 4000",
"assigned_name": "Krunal Patel",
"created_date": null,
"primary_address_id": 0,
"secondary_address_id": 0,
"modified_date": null,
"contact_modified_date": "0000-00-00 00:00:00",
"created_by": 1
}
its not json_encode fault.if you run below code you can see that in less than 3 seconds it gonna finished.its because of output size and rendering time that you show to the user.you can paginate your output and don't show all of them together
<?php
$str = [];
for($i = 0;$i<4000;$i++){
$str[] = "sample data";
}
$json = json_encode($str);
echo strlen($json);
My response code :
Shpping : [
{
"id": "1",
"name": "Dress",
"deleted_at": null,
"created_at": null,
"updated_at": null,
"minicomp": [
{
"id": "1",
"cname": "basic",
"base_id": 44
},
{
"id": "2",
"cname": "Shirt",
"base_id": 177444
},
{
"id": "3",
"cname": "Pants",
"base_id": 444
}
]
}
];
I want to access base_id of of every object in child array 'minicomp' whose parent is 'Shipping'. How can I access it?
First convert your json into array using json_decode().Like this..
$json =<your json>;
$array = json_decode($json,true);
Then
echo $array['Shpping '][0]]['minicomp'][0]['id'];//outputs 1
Example:
<?php
$json = '[{
"id": "1",
"name": "Dress",
"deleted_at": null,
"created_at": null,
"updated_at": null,
"minicomp": [{
"id": "1",
"cname": "basic",
"base_id": 44
}, {
"id": "2",
"cname": "Shirt",
"base_id": 177444
}, {
"id": "3",
"cname": "Pants",
"base_id": 444
}]
}]';
$array = json_decode($json,true);
//print_r($array);
$minicomp = $array[0]['minicomp'];
echo $minicomp[0]['id'];
echo $minicomp[1]['id'];
?>
UPDATE
For getting all ids.Without defining indexes.Use foreach loop:
foreach($minicomp as $key=>$value){
echo $minicomp[$key]['id']."<br/>";
}