This question already has an answer here:
How to extract and access data from JSON with PHP?
(1 answer)
Closed 16 days ago.
I get this json data from football api
[
{
"id": "/sport/football/english-premier-league/everton-v-arsenal/32031876",
"name": "Everton v Arsenal",
"team1": {
"name": "Everton",
"score": "",
"sets": null,
"games": null
},
"team2": {
"name": "Arsenal",
"score": "",
"sets": null,
"games": null
},
"start_datetime": "2023-02-04 12:30:00 UTC",
"is_live": false,
"live_time": null,
"odds": {
"1": "7.500",
"2": "1.444",
"X": "4.333"
}
},
{
"id": "/sport/football/english-premier-league/wolves-v-liverpool/32031228",
"name": "Wolves v Liverpool",
"team1": {
"name": "Wolves",
"score": "",
"sets": null,
"games": null
},
"team2": {
"name": "Liverpool",
"score": "",
"sets": null,
"games": null
},
"start_datetime": "2023-02-04 15:00:00 UTC",
"is_live": false,
"live_time": null,
"odds": {
"1": "4.100",
"2": "1.833",
"X": "3.900"
}
},
{
"id": "/sport/football/english-premier-league/aston-villa-v-leicester/32031878",
"name": "Aston Villa v Leicester",
"team1": {
"name": "Aston Villa",
"score": "",
"sets": null,
"games": null
},
"team2": {
"name": "Leicester",
"score": "",
"sets": null,
"games": null
},
"start_datetime": "2023-02-04 15:00:00 UTC",
"is_live": false,
"live_time": null,
"odds": {
"1": "1.950",
"2": "3.900",
"X": "3.500"
}
},
{
"id": "/sport/football/english-premier-league/brighton-v-bournemouth/32031880",
"name": "Brighton v Bournemouth",
"team1": {
"name": "Brighton",
"score": "",
"sets": null,
"games": null
},
"team2": {
"name": "Bournemouth",
"score": "",
"sets": null,
"games": null
},
"start_datetime": "2023-02-04 15:00:00 UTC",
"is_live": false,
"live_time": null,
"odds": {
"1": "1.333",
"2": "9.000",
"X": "5.000"
}
},
{
"id": "/sport/football/english-premier-league/man-utd-v-crystal-palace/32031894",
"name": "Man Utd v Crystal Palace",
"team1": {
"name": "Man Utd",
"score": "",
"sets": null,
"games": null
},
"team2": {
"name": "Crystal Palace",
"score": "",
"sets": null,
"games": null
},
"start_datetime": "2023-02-04 15:00:00 UTC",
"is_live": false,
"live_time": null,
"odds": {
"1": "1.364",
"2": "9.500",
"X": "5.000"
}
}
]
I want get specific data from json using php code my php code
<?php
$curl = curl_init();
curl_setopt_array($curl, [
CURLOPT_URL => "https://betfair-sportsbook.p.rapidapi.com/matches-by-competition?competitionid=%2Fsport%2Ffootball%2Fenglish-premier-league%2F10932509&lang=en",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "GET",
CURLOPT_HTTPHEADER => [
"X-RapidAPI-Host: betfair-sportsbook.p.rapidapi.com",
"X-RapidAPI-Key: 525b88983fmshf83037428bcd3a1p153499jsncc02a790c215"
],
]);
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $response;
}
?>
I want Out Put like this for all array :
Match Name : Everton Vs Arsenal
Start : 2023-02-04 12:30:00 UTC
I want Out Put like this for all array :
Match Name : Everton Vs Arsenal
Start : 2023-02-04 12:30:00 UTC
Use json_decode on the $response data.
https://www.w3schools.com/Php/func_json_decode.asp
You can do something like this to turn that JSON object into an array: json_decode($response, true);
Then you can access the fields as you would any associative array.
Related
I get a list of invoices through api. See:
<?php
$url = "https://app.domain.tld/api/v2/accounts/censored/invoices.json?status=uncollectible";
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$headers = array(
"User-Agent: YourApp (yourname#example.com)",
"Authorization: Basic censored==",
);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
echo $resp = curl_exec($curl);
curl_close($curl);
?>
This data will be returned to me in JSON:
[{
"id": 23487088,
"custom_id": null,
"proforma": false,
"partial_proforma": false,
"number": "2022-05-0008",
"number_format_id": 363568,
"variable_symbol": "2022050008",
"your_name": "Censored s.r.o.",
"your_street": "Street 1801/22",
"your_street2": null,
"your_city": "Praha",
"your_zip": "10900",
"your_country": "CZ",
"your_registration_no": "00055222",
"your_vat_no": "CZ00055222",
"your_local_vat_no": null,
"client_name": "Firma s.r.o.",
"client_street": "Street 508/2",
"client_street2": null,
"client_city": "Prague",
"client_zip": "111 22",
"client_country": "CZ",
"client_registration_no": "0000000",
"client_vat_no": "",
"client_local_vat_no": "",
"subject_id": 14471217,
"subject_custom_id": null,
"generator_id": null,
"related_id": null,
"correction": false,
"correction_id": null,
"paypal": false,
"gopay": false,
"token": "zuqpytRSBg",
"status": "uncollectible",
"order_number": "",
"issued_on": "2022-05-13",
"taxable_fulfillment_due": "2022-05-13",
"due": 7,
"due_on": "2022-05-20",
"sent_at": null,
"paid_at": null,
"reminder_sent_at": null,
"accepted_at": null,
"cancelled_at": null,
"webinvoice_seen_at": null,
"note": "",
"footer_note": "Společnost je zapsána v obchodním rejstříku vedeném Městským soudem v Praze oddíl C, vložka 000000.",
"private_note": null,
"tags": [],
"bank_account": "0000000000/2010",
"iban": "CZ000000000000000000000",
"swift_bic": "FIOBCZPPXXX",
"show_already_paid_note_in_pdf": false,
"payment_method": "bank",
"hide_bank_account": false,
"currency": "CZK",
"exchange_rate": "1.0",
"language": "cz",
"transferred_tax_liability": false,
"eu_electronic_service": false,
"oss": "disabled",
"vat_price_mode": "without_vat",
"supply_code": "",
"subtotal": "3000.0",
"total": "3630.0",
"native_subtotal": "3000.0",
"native_total": "3630.0",
"remaining_amount": "3630.0",
"remaining_native_amount": "3630.0",
"paid_amount": "0.0",
"eet": false,
"eet_cash_register": null,
"eet_store": null,
"eet_records": [],
"lines": [{
"id": 52921163,
"name": "IT services",
"quantity": "1.0",
"unit_name": "",
"unit_price": "3000.0",
"vat_rate": 21,
"unit_price_without_vat": "3000.0",
"unit_price_with_vat": "3630.0"
}],
"attachment": null,
"html_url": "https://app.fakturoid.cz/censored/invoices/23487088",
"public_html_url": "https://app.fakturoid.cz/censored/p/zuqpytRSBg/2022-05-0008",
"url": "https://app.fakturoid.cz/api/v2/accounts/censored/invoices/23487088.json",
"pdf_url": "https://app.fakturoid.cz/api/v2/accounts/censored/invoices/23487088/download.pdf",
"subject_url": "https://app.fakturoid.cz/api/v2/accounts/censored/subjects/14471217.json",
"created_at": "2022-05-21T16:27:32.488+02:00",
"updated_at": "2022-05-21T16:27:35.464+02:00"
}, {
"id": 23487082,
"custom_id": null,
"proforma": false,
"partial_proforma": false,
"number": "2022-05-0007",
"number_format_id": 363568,
"variable_symbol": "2022050007",
"your_name": "censored s.r.o.",
"your_street": "censored",
"your_street2": null,
"your_city": "Praha",
"your_zip": "10900",
"your_country": "CZ",
"your_registration_no": "00055222",
"your_vat_no": "CZ00055222",
"your_local_vat_no": null,
"client_name": "Firma s.r.o.",
"client_street": "Street 508/2",
"client_street2": null,
"client_city": "Prague",
"client_zip": "111 22",
"client_country": "CZ",
"client_registration_no": "0000000",
"client_vat_no": "",
"client_local_vat_no": "",
"subject_id": 14471217,
"subject_custom_id": null,
"generator_id": null,
"related_id": null,
"correction": false,
"correction_id": null,
"paypal": false,
"gopay": false,
"token": "7xIDMf64iQ",
"status": "uncollectible",
"order_number": "",
"issued_on": "2022-05-04",
"taxable_fulfillment_due": "2022-05-04",
"due": 1,
"due_on": "2022-05-05",
"sent_at": null,
"paid_at": null,
"reminder_sent_at": null,
"accepted_at": null,
"cancelled_at": null,
"webinvoice_seen_at": null,
"note": "",
"footer_note": "Společnost je zapsána v obchodním rejstříku vedeném Městským soudem v Praze oddíl C, vložka 000000.",
"private_note": null,
"tags": [],
"bank_account": "000000000/2010",
"iban": "CZ000000000000000000000",
"swift_bic": "FIOBCZPPXXX",
"show_already_paid_note_in_pdf": false,
"payment_method": "bank",
"hide_bank_account": false,
"currency": "CZK",
"exchange_rate": "1.0",
"language": "cz",
"transferred_tax_liability": false,
"eu_electronic_service": false,
"oss": "disabled",
"vat_price_mode": "without_vat",
"supply_code": "",
"subtotal": "5000.0",
"total": "6050.0",
"native_subtotal": "5000.0",
"native_total": "6050.0",
"remaining_amount": "6050.0",
"remaining_native_amount": "6050.0",
"paid_amount": "0.0",
"eet": false,
"eet_cash_register": null,
"eet_store": null,
"eet_records": [],
"lines": [{
"id": 52921141,
"name": "IT services",
"quantity": "1.0",
"unit_name": "",
"unit_price": "5000.0",
"vat_rate": 21,
"unit_price_without_vat": "5000.0",
"unit_price_with_vat": "6050.0"
}],
"attachment": null,
"html_url": "https://app.fakturoid.cz/censored/invoices/23487082",
"public_html_url": "https://app.fakturoid.cz/censored/p/7xIDMf64iQ/2022-05-0007",
"url": "https://app.fakturoid.cz/api/v2/accounts/censored/invoices/23487082.json",
"pdf_url": "https://app.fakturoid.cz/api/v2/accounts/censored/invoices/23487082/download.pdf",
"subject_url": "https://app.fakturoid.cz/api/v2/accounts/censored/subjects/14471217.json",
"created_at": "2022-05-21T16:25:51.916+02:00",
"updated_at": "2022-05-21T16:26:54.323+02:00"
}]
The problem is that I can't throw it into a nice boostrap table, columns using PHP and possibly save it to a database. I tried it this way, but I did not meet with success.
<?php
$data = json_decode($resp->data, true);
foreach ($data as $key => $value) {
$invoice_id = $value['array']['id']; // id invoice
$invoice_status = $value['array']['status']; // paid, unpaid, uncollectible etc...
$invoice_price = $value['array']['total']; // total price with VAT
}
?>
But I'm not successful. I'm getting a error:
Error: Trying to get property 'data' of non-object
I'm at the end, please help
please use this php code, your array contains objects
$data = json_decode($resp);
foreach ($data as $key => $value) {
$invoice_id = $value->id; // id invoice
$invoice_status = $value->status; // paid, unpaid, uncollectible etc...
$invoice_price = $value->total; // total price with VAT
}
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 }?>
So I have a huge JSON chunk of data that I need to parse. It has been converted to a PHP array with json_decode. Below is one element of the data object in the PHP array. There are hundreds of these elements, below is just one:
'{
"data": [
{
"id": 3215,
"user_id": {
"id": 99106,
"name": "Rusty shackleford",
"email": "Rusty.shackleford#company.com",
"has_pic": true,
"pic_hash": "someHash",
"active_flag": true,
"value": 99106
},
"person_id": {
"name": "rusty shackleford",
"email": [
{
"label": "Work",
"value": "rusty shackleford#email.com",
"primary": true
}
],
"phone": [
{
"label": "Fax",
"value": "666-666-6666",
"primary": false
},
{
"label": "main",
"value": "666-666-6666",
"primary": false
},
{
"label": "main",
"value": "666-666-6666",
"primary": true
}
],
"value": 666
},
"org_id": {
"name": "shackleford, Inc.",
"people_count": 23,
"cc_email": "rusty#6theShack.com",
"value": 1013
},
"stage_id": 8,
"title": "rusty\'s Projects",
"value": 0,
"currency": "USD",
"add_time": "2013-01-15 00:00:00",
"update_time": "2015-07-07 14:28:15",
"stage_change_time": "2013-10-30 14:43:09",
"active": true,
"deleted": false,
"status": "open",
"next_activity_date": "2015-07-07",
"next_activity_time": null,
"next_activity_id": 3771,
"last_activity_id": 252,
"last_activity_date": "2013-11-16",
"lost_reason": null,
"visible_to": "3",
"close_time": null,
"pipeline_id": 1,
"won_time": null,
"lost_time": null,
"products_count": null,
"files_count": null,
"notes_count": 21,
"followers_count": 1,
"email_messages_count": null,
"activities_count": 2,
"done_activities_count": 1,
"undone_activities_count": 1,
"reference_activities_count": 0,
"participants_count": 1,
"b98336b40c8420dc2f1401d6451b1b47198eee6d": "",
"17a14a9da9815451ff5ffc669d407e8b0376b06b": 4616,
"3eedd4fd08f44a72d911dc4934a6916f3b31911b": "",
"52ede287f6c55eb6b12821ca24f74098779abdce": "",
"13916ba291ab595f27aefbff8b6c43a3fb467b72": "shackleford LLP",
"6330684838740625ea6a7d260f102a1961b2fae1": "shackleford, Inc.",
"ded823307920bf70cea49c45684148fd295e179a": "",
"ed35f69413af7156058d1081321e7bb227577eef_lat": null,
"ed35f69413af7156058d1081321e7bb227577eef_long": null,
"ed35f69413af7156058d1081321e7bb227577eef_subpremise": null,
"ed35f69413af7156058d1081321e7bb227577eef_street_number": null,
"ed35f69413af7156058d1081321e7bb227577eef_route": null,
"ed35f69413af7156058d1081321e7bb227577eef_sublocality": null,
"ed35f69413af7156058d1081321e7bb227577eef_locality": null,
"ed35f69413af7156058d1081321e7bb227577eef_admin_area_level_1": null,
"ed35f69413af7156058d1081321e7bb227577eef_admin_area_level_2": null,
"ed35f69413af7156058d1081321e7bb227577eef_country": null,
"ed35f69413af7156058d1081321e7bb227577eef_postal_code": null,
"ed35f69413af7156058d1081321e7bb227577eef_formatted_address": null,
"09358ea07e1a1007d24bc068c723bf1f79e8359d": null,
"expected_close_date": null,
"7cce64c3abb5f28a260bc9d6719a43367bae5dfe": null,
"stage_order_nr": 10,
"person_name": "shackleford",
"org_name": "shackleford, Inc.",
"next_activity_subject": "pocket Sand!",
"next_activity_type": "task",
"next_activity_duration": "00:00:00",
"next_activity_note": "",
"formatted_value": "$0",
"weighted_value": 0,
"formatted_weighted_value": "$0",
"rotten_time": null,
"owner_name": "Rusty shackleford",
"cc_email": "rusty+stuff3215#shackleford.com",
"org_hidden": false,
"person_hidden": false
}
]
}'
Below is some of my code so far:
$response = json_decode($json_response, true);
//$ksortResult = ksort($response['data']);
foreach($response as $field){
echo $field;
}
If anyone can help me step through the json object with arrays, I'd greatly appreciate it. Also, I'm trying to sort the data based on keys before I step through it.
The desired output would be like the one below:
id|user_id|person_id|org_id|stage_id|title|value|currency|add_time|update_time|stage_change_time|active|deleted|status|next_activity_date|next_activity_time|next_activity_id|last_activity_id|last_activity_date|lost_reason|visible_to|close_time|pipeline_id|won_time|lost_time|products_count|files_count|notes_count|followers_count|email_messages_count|activities_count|done_activities_count|undone_activities_count|reference_activities_count|participants_count|b98336b40c8420dc2f1401d6451b1b47198eee6d|_17a14a9da9815451ff5ffc669d407e8b0376b06b|_3eedd4fd08f44a72d911dc4934a6916f3b31911b|_52ede287f6c55eb6b12821ca24f74098779abdce|_13916ba291ab595f27aefbff8b6c43a3fb467b72|_6330684838740625ea6a7d260f102a1961b2fae1|ded823307920bf70cea49c45684148fd295e179a ed35f69413af7156058d1081321e7bb227577eef_lat ed35f69413af7156058d1081321e7bb227577eef_long|ed35f69413af7156058d1081321e7bb227577eef_subpremise|ed35f69413af7156058d1081321e7bb227577eef_street_number|ed35f69413af7156058d1081321e7bb227577eef_route|ed35f69413af7156058d1081321e7bb227577eef_sublocality|ed35f69413af7156058d1081321e7bb227577eef_locality|ed35f69413af7156058d1081321e7bb227577eef_admin_area_level_1|ed35f69413af7156058d1081321e7bb227577eef_admin_area_level_2|ed35f69413af7156058d1081321e7bb227577eef_country|ed35f69413af7156058d1081321e7bb227577eef_postal_code|ed35f69413af7156058d1081321e7bb227577eef_formatted_address|_09358ea07e1a1007d24bc068c723bf1f79e8359d|expected_close_date|_7cce64c3abb5f28a260bc9d6719a43367bae5dfe|stage_order_nr|person_name org_name|next_activity_subject|next_activity_type|next_activity_duration|next_activity_note|formatted_value|weighted_value|formatted_weighted_value|rotten_time owner_name|cc_email|org_hidden|person_hidden|user_name|user_email|person_phone_1 person_phone_2|person_phone_3|org_people_count
3215|99106|666|1013|8|rusty's Projects|0|USD|1/15/2013 0:00|7/7/2015 14:28|10/30/2013 14:43|TRUE|FALSE|open|7/7/2015|null|3771|252|11/16/2013|null|3|null|1|null|null|null|null|21|1|null|2|1|1|0|1||4616|||shackleford LLP|shackleford,Inc.||null|null|null|null|null|null|null|null|null|null|null|null|null|null|null|10|shackleford|shackleford, Inc.|pocket Sand!|task|0:00:00||$0|0|$0|0:00:00|Rusty shackleford|rusty+stuff3215#shackleford.com|FALSE|FALSE|Rusty shackleford|Rusty.shackleford#company.com|666-666-6666|666-666-6666|666-666-6666|23
So if I understand correctly you want to flatten the json structure? If that's the case, take a look at look at array_walk_recursive:
http://php.net/manual/en/function.array-walk-recursive.php
Which would look something like this:
$newArray = [];
array_walk_recursive( $formerlyJsonArray,
function($value, $key) use (&$newArray) {
$newArray[$key] = $value;
});
Or take a look at array_reduce:
http://php.net/manual/en/function.array-reduce.php
I have really have troubles trying to work out why this is not working, and it seems like it should be easy, but just cannot seem to get it.
All I am looking to do is grab the sku field (which is VBP-01 below).
{
"variants": [
{
"id": 2314578,
"created_at": "2014-07-29T07:22:18.921Z",
"updated_at": "2015-05-21T15:42:42.136Z",
"product_id": 1188647,
"default_ledger_account_id": null,
"buy_price": "124.0",
"committed_stock": "0",
"incoming_stock": "3",
"composite": false,
"description": null,
"is_online": false,
"keep_selling": false,
"last_cost_price": "124.0",
"manage_stock": true,
"max_online": null,
"moving_average_cost": "124",
"name": "Lanparte battery pinch VBP-01",
"online_ordering": false,
"opt1": null,
"opt2": null,
"opt3": null,
"position": 1,
"product_name": "Lanparte V-Mount Battery Pinch",
"product_status": "active",
"product_type": null,
"retail_price": "0.0",
"sellable": true,
"sku": "VBP-01",
"status": "active",
"stock_on_hand": "1",
"supplier_code": "VBP-01",
"taxable": true,
"upc": null,
"weight": null,
"wholesale_price": "0.0",
"image_ids": [],
"variant_prices": [
{
"price_list_id": "buy",
"value": "124.0"
},
{
"price_list_id": "retail",
"value": "0.0"
},
{
"price_list_id": "wholesale",
"value": "0.0"
}
],
"locations": [
{
"location_id": 16377,
"stock_on_hand": "1",
"committed": null,
"incoming": "3",
"bin_location": null,
"reorder_point": 3
}
],
"prices": {
"buy": "124.0",
"retail": "0.0",
"wholesale": "0.0"
},
"stock_levels": {
"16377": "1.0"
},
"committed_stock_levels": {},
"incoming_stock_levels": {
"16377": "3.0"
}
}
],
"meta": {
"total": 1
}
}
Currently I using the following code with no luck
$url = "https://api.tradegecko.com/variants?sku=VBP-01";
$data = file_get_contents($url, false, $context);
$json = json_decode($data);
print $json->{'variant'}->{'sku'};
What I am doing wrong?
Just
echo $json->{'variants'}[0]->{'sku'};
In a loop
foreach ($json->variants as $variants) {
echo $variants->sku;
}
I'm getting the latest tweets and the results come back like so:
[{
"created_at": "Wed Aug 28 11:50:22 +0000 2013",
"id": 372687598952919040,
"id_str": "372687598952919040",
"text": "\"I fear we'll get ourselves involved in another endless conflict\" - Ukip's #Nigel_Farage on UK's #Syria decision http:\/\/t.co\/3iMlO9BHks",
"source": "<a href=\"http:\/\/www.bbc.co.uk\/news\/\" rel=\"nofollow\">BBC News<\/a>",
"truncated": false,
"in_reply_to_status_id": null,
"in_reply_to_status_id_str": null,
"in_reply_to_user_id": null,
"in_reply_to_user_id_str": null,
"in_reply_to_screen_name": null,
"user": {
"id": 612473,
"id_str": "612473",
"name": "BBC News (UK)",
"screen_name": "BBCNews",
"location": "London",
"description": "News, features and analysis from BBC News (UK edition). For world edition, follow #BBCWorld. For breaking news, follow #BBCBreaking. Latest sport news #BBCSport",
"url": "http:\/\/t.co\/2XmxtfHbzW",
"entities": {
"url": {
"urls": [{
"url": "http:\/\/t.co\/2XmxtfHbzW",
"expanded_url": "http:\/\/www.bbc.co.uk\/news",
"display_url": "bbc.co.uk\/news",
"indices": [0, 22]
}]
},
"description": {
"urls": []
}
},
"protected": false,
"followers_count": 1886892,
"friends_count": 91,
"listed_count": 24941,
"created_at": "Mon Jan 08 08:05:57 +0000 2007",
"favourites_count": 0,
"utc_offset": 3600,
"time_zone": "London",
"geo_enabled": false,
"verified": true,
"statuses_count": 190164,
"lang": "en",
"contributors_enabled": false,
"is_translator": false,
"profile_background_color": "FFFFFF",
"profile_background_image_url": "http:\/\/a0.twimg.com\/profile_background_images\/571083158\/l7tnxw8xy058c4rm6e4f.jpeg",
"profile_background_image_url_https": "https:\/\/si0.twimg.com\/profile_background_images\/571083158\/l7tnxw8xy058c4rm6e4f.jpeg",
"profile_background_tile": false,
"profile_image_url": "http:\/\/a0.twimg.com\/profile_images\/2186831845\/128x128_twitter_bbc_uk_normal.jpg",
"profile_image_url_https": "https:\/\/si0.twimg.com\/profile_images\/2186831845\/128x128_twitter_bbc_uk_normal.jpg",
"profile_banner_url": "https:\/\/pbs.twimg.com\/profile_banners\/612473\/1357232373",
"profile_link_color": "1F527B",
"profile_sidebar_border_color": "CCCCCC",
"profile_sidebar_fill_color": "FFFFFF",
"profile_text_color": "5A5A5A",
"profile_use_background_image": true,
"default_profile": false,
"default_profile_image": false,
"following": null,
"follow_request_sent": false,
"notifications": null
},
"geo": null,
"coordinates": null,
"place": null,
"contributors": null,
"retweet_count": 28,
"favorite_count": 12,
"entities": {
"hashtags": [{
"text": "Syria",
"indices": [97, 103]
}],
"symbols": [],
"urls": [{
"url": "http:\/\/t.co\/3iMlO9BHks",
"expanded_url": "http:\/\/bbc.in\/13YTz5f",
"display_url": "bbc.in\/13YTz5f",
"indices": [113, 135]
}],
"user_mentions": [{
"screen_name": "Nigel_Farage",
"name": "Nigel Farage",
"id": 19017675,
"id_str": "19017675",
"indices": [75, 88]
}]
},
"favorited": false,
"retweeted": false,
"possibly_sensitive": false,
"lang": "en"
}, {
"created_at": "Wed Aug 28 11:27:11 +0000 2013",
"id": 372681763640061952,
"id_str": "372681763640061952",
"text": "International agreement, legal basis, support in country - #HarrietHarman on criteria needed to support Syria action http:\/\/t.co\/I5fWeyt9gl",
"source": "<a href=\"http:\/\/www.bbc.co.uk\/news\/\" rel=\"nofollow\">BBC News<\/a>",
"truncated": false,
"in_reply_to_status_id": null,
"in_reply_to_status_id_str": null,
"in_reply_to_user_id": null,
"in_reply_to_user_id_str": null,
"in_reply_to_screen_name": null,
"user": {
"id": 612473,
"id_str": "612473",
"name": "BBC News (UK)",
"screen_name": "BBCNews",
"location": "London",
"description": "News, features and analysis from BBC News (UK edition). For world edition, follow #BBCWorld. For breaking news, follow #BBCBreaking. Latest sport news #BBCSport",
"url": "http:\/\/t.co\/2XmxtfHbzW",
"entities": {
"url": {
"urls": [{
"url": "http:\/\/t.co\/2XmxtfHbzW",
"expanded_url": "http:\/\/www.bbc.co.uk\/news",
"display_url": "bbc.co.uk\/news",
"indices": [0, 22]
}]
},
"description": {
"urls": []
}
},
"protected": false,
"followers_count": 1886892,
"friends_count": 91,
"listed_count": 24941,
"created_at": "Mon Jan 08 08:05:57 +0000 2007",
"favourites_count": 0,
"utc_offset": 3600,
"time_zone": "London",
"geo_enabled": false,
"verified": true,
"statuses_count": 190164,
"lang": "en",
"contributors_enabled": false,
"is_translator": false,
"profile_background_color": "FFFFFF",
"profile_background_image_url": "http:\/\/a0.twimg.com\/profile_background_images\/571083158\/l7tnxw8xy058c4rm6e4f.jpeg",
"profile_background_image_url_https": "https:\/\/si0.twimg.com\/profile_background_images\/571083158\/l7tnxw8xy058c4rm6e4f.jpeg",
"profile_background_tile": false,
"profile_image_url": "http:\/\/a0.twimg.com\/profile_images\/2186831845\/128x128_twitter_bbc_uk_normal.jpg",
"profile_image_url_https": "https:\/\/si0.twimg.com\/profile_images\/2186831845\/128x128_twitter_bbc_uk_normal.jpg",
"profile_banner_url": "https:\/\/pbs.twimg.com\/profile_banners\/612473\/1357232373",
"profile_link_color": "1F527B",
"profile_sidebar_border_color": "CCCCCC",
"profile_sidebar_fill_color": "FFFFFF",
"profile_text_color": "5A5A5A",
"profile_use_background_image": true,
"default_profile": false,
"default_profile_image": false,
"following": null,
"follow_request_sent": false,
"notifications": null
},
"geo": null,
"coordinates": null,
"place": null,
"contributors": null,
"retweet_count": 17,
"favorite_count": 4,
"entities": {
"hashtags": [],
"symbols": [],
"urls": [{
"url": "http:\/\/t.co\/I5fWeyt9gl",
"expanded_url": "http:\/\/bbc.in\/13YQD8O",
"display_url": "bbc.in\/13YQD8O",
"indices": [117, 139]
}],
"user_mentions": [{
"screen_name": "HarrietHarman",
"name": "Harriet Harman",
"id": 19977759,
"id_str": "19977759",
"indices": [59, 73]
}]
},
"favorited": false,
"retweeted": false,
"possibly_sensitive": false,
"lang": "en"
}]
How can I use this so I can cherry pick tweets from the array, eg. $tweets[2]; I've tried json_decode but no luck.
You can try passing a second parameter to json_decode, that will dump all json data as an associative array
link
If you try to store the JSON output in a string, it will fail due to the unescaped single quotes in it.
For example, you have the following text in the JSON output:
"text": "\"I fear we'll get ourselves involved in another endless conflict\"
//------^
So, if you try to assign the JSON to a string, it will fail and produce a parse error because of the single quotes in it. Because your JSON contains double-quotes, you can't use that, either.
To tell PHP to ignore the quotes and interpret it as a string, you can use the heredoc syntax, like so:
$string = <<<JSON
... json ...
JSON;
$json = json_decode($string);
echo $json[0]->text."\n";
echo $json[1]->text."\n";
Note: if you want to get an associative array instead, you can pass the the second paramter for json_decode() as TRUE.
Working demo!