I am using Tropo Web API, to get result from a chat application, i redirected my JSON response to my server side PHP file(http://myhost.in/vj/app3.php?tropo-engine=json), the JSON response is coming correctly but i am not able to fetch data from that using PHP,
the JSON response is as follows..
{
"result": {
"actions":
[
{
"attempts": 2,
"concept": "mumbai",
"confidence": 100,
"disposition": "SUCCESS",
"interpretation": "mumbai",
"name": "city",
"utterance": "mumbai",
"value": "mumbai",
"xml": "<?xml version=\"1.0\" encoding=\"UTF-8\"?><result grammar=\"1#6ac61bfd.vxmlgrammar\"><interpretation grammar=\"1#6ac61bfd.vxmlgrammar\" confidence=\"100\"><instance>mumbai<\/instance><input mode=\"voice\" confidence=\"100\" timestamp-start=\"1970-01-01T00:00:00.000\" timestamp-end=\"1970-01-01T00:00:00.000\">mumbai<extensions><word-confidence> 100 <\/word-confidence><\/extensions><\/input><extensions><probability> 0 <\/probability><nl-probability> 0 <\/nl-probability><necessary-word-confidence> 0 <\/necessary-word-confidence><\/extensions><\/interpretation><\/result>\r\n\r\n"
},
{
"attempts": 1,
"concept": "cricket",
"confidence": 100,
"disposition": "SUCCESS",
"interpretation": "cricket",
"name": "sports",
"utterance": "cricket",
"value": "cricket",
"xml": "<?xml version=\"1.0\" encoding=\"UTF-8\"?><result grammar=\"2#6ac61bfd.vxmlgrammar\"><interpretation grammar=\"2#6ac61bfd.vxmlgrammar\" confidence=\"100\"><instance>cricket<\/instance><input mode=\"voice\" confidence=\"100\" timestamp-start=\"1970-01-01T00:00:00.000\" timestamp-end=\"1970-01-01T00:00:00.000\">cricket<extensions><word-confidence> 100 <\/word-confidence><\/extensions><\/input><extensions><probability> 0 <\/probability><nl-probability> 0 <\/nl-probability><necessary-word-confidence> 0 <\/necessary-word-confidence><\/extensions><\/interpretation><\/result>\r\n\r\n"
}
],
"callId": "b546e03db1ccfd2f0e8c58d970539501",
"complete": true,
"error": null,
"sequence": 1,
"sessionDuration": 11,
"sessionId": "ed6abc73b9c434385ea8cd8004c9ed0c",
"state": "ANSWERED"
}
}
the PHP code that i am using...
$json = file_get_contents("php://input");
$result = json_decode($json);
$value =$result->result->actions->value;
but i am getting null in the variable $value. How will get the value for city and sports as well..??
It is because $result->result->actions is an array. Try $result->result->actions[0]->value
Related
$filtered_restros= new \Illuminate\Pagination\CursorPaginator($restaurants, 1);
$data['message'] = "Restaurants fetched successfully";
$data['status'] = "success";
$data['data'] = $filtered_restros;
I did this code and i'm getting fallowing results
{
"message": "Restaurants fetched successfully",
"status": "success",
"data": {
"data": [
{
"id": 5,
"name": "HB Town Restro",
"email": "2321efsd#gmail.com",
"phone_number": "12",
"mobile_number": "454554354",
"address": "hjgjghioiu",
"pincode": "4400255241653",
"latitude": "21.150964",
"longitude": "79.150516",
"restro_type": 1,
"cuisine_type": "American",
"book_now_btn": 1,
"queue_btn": 0,
"is_saved": 0,
"restro_cuisines": [
{
"cuisine_id": 5,
"cuisine_name": "North indian"
}
],
"seating_options": [
"Cafeteria",
"fghfghf",
"Cafeterias",
"indoor"
],
"description": "gj",
"menu_category": "5",
"parking": "Onsite",
"image": "http://localhost/projectx/public/restaurants/hb.jpg",
"status": 1
}
],
"path": "/",
"per_page": 1,
"next_page_url": "/?cursor=eyJfcG9pbnRzVG9OZXh0SXRlbXMiOnRydWV9",
"prev_page_url": null
}
}
after hitting the "next_page_url"
http://localhost/projectx/api/user/explore_all_restaurants?cursor=eyJfcG9pbnRzVG9OZXh0SXRlbXMiOnRydWV9
this printing same results as above means cursor pagination is not working.
When i did same thing using eloquent
$users = DB::table('restros')->orderBy('id')->cursorPaginate(15);
its working properly and pagination is also working and full next page url are automatically generating. but its using eloquent and i want to do the cursor pagination on my processed array and its not working properly.
In short i'm asking how to do cursor pagination on custom array.
I get the following data from a webhook:
{
"id": 1,
"date_created": "2017-08-31T11:26:38.000Z",
"date_approved": "2017-08-31T11:26:38.000Z",
"date_last_updated": "2017-08-31T11:26:38.000Z",
"money_release_date": "2017-09-14T11:26:38.000Z",
"payment_method_id": "account_money",
"payment_type_id": "credit_card",
"status": "approved",
"status_detail": "accredited",
"currency_id": "BRL",
"description": "Pago Pizza",
"collector_id": 2,
"payer": {
"id": 123,
"email": "afriend#gmail.com",
"identification": {
"type": "DNI",
"number": 12345678
},
"type": "customer"
},
"metadata": {},
"additional_info": {},
"transaction_amount": 250,
"transaction_amount_refunded": 0,
"coupon_amount": 0,
"transaction_details": {
"net_received_amount": 250,
"total_paid_amount": 250,
"overpaid_amount": 0,
"installment_amount": 250
},
"installments": 1,
"card": {}
}
I get this data from the following expression:
$payment = null;
$payment = MercadoPago\Payment::find_by_id($_GET["data_id"]);
And I access the data as below:
$pStatus = $payment->status;
$payID = $payment->id;
But I still did not figure out how to access the nested values as for instance, the email.
I tried to convert the object to an array as in:
$responseArray = $payment->toArray();
So I could access the email using:
$responseArray['payer']['email']
But not working...
I need to read all nested values.
Assistance welcome.
This question already has an answer here:
How to extract and access data from JSON with PHP?
(1 answer)
Closed 4 years ago.
I'm new into PHP and JSON and I have a problem, I want to retrieve a item and value from a JSON:
{
"status": true,
"webhook_type": 100,
"data": {
"product": {
"id": "lSEADIQ",
"attachment_id": null,
"title": "Registration",
"description": null,
"image": null,
"unlisted": false,
"type": "service",
"price": 1,
"currency": "EUR",
"email": {
"enabled": false
},
"stock_warning": 0,
"quantity": {
"min": 1,
"max": 1
},
"confirmations": 1,
"custom_fields": [
{
"name": "Forum username",
"type": "text",
"required": true
}
],
"gateways": [
"Bitcoin"
],
"webhook_urls": [],
"dynamic_url": "",
"position": null,
"created_at": "2018-10-01 12:51:12",
"updated_at": "2018-10-01 12:55:46",
"stock": 9223372036854776000,
"accounts": []
},
"order": {
"id": "8e23b496-121a-4dc6-8ec4-c45835680db2",
"created_at": "Tue, 02 Oct 2018 00:54:56 +0200",
"paid_at": null,
"transaction_id": null,
"confirmations": 1,
"required_confirmations": 3,
"received_amount": 0,
"crypto_address": "1NeNQws7JLbTr6bjekfeaXSV7XiyRsv7V8",
"crypto_amount": "0.4815",
"quantity": 1,
"price": 19.99,
"currency": "EUR",
"exchange_rate": "1.21",
"gateway": "BTC",
"email": "webhook#site.gg",
"ip_address": "123.456.789.111",
"agent": {
"geo": {
"ip": "214.44.18.6",
"iso_code": "US",
"country": "United States"
},
"data": {
"is_mobile": false,
"is_table": false,
"is_desktop": true,
"browser": {
"name": "Chrome",
"version": "63.0.3239.132"
}
}
},
"custom_fields": [
{
"name": "user_id",
"value": 184191
}
],
"user_agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_3)"
}
}
}
I want to retrieve items from data -> order, for example "id" or "ip_address".
Thank you for read this, I hope someone can help me in this, because I'm lost, I started to code very recently and I'm trying to learn a lot.
Regards!
Where test.json is the json you uploaded, place it in a file named test.json and ensure its placed in the same directory.
<?php
$load = file_get_contents("test.json") or die("JSON load failed");
$json_a = json_decode($load, true);
print $json_a['data']['order']['ip_address'] . "\n";
?>
Gives:
123.456.789.111
My answer reads the JSON from a file as were it dumped directly in your code, which indeed it could be, it would make the code less readable and your file more messy.
If you dont want to place the file in the same directory, simply specify the full file path. E.g. file_get_contents("this/dir/here/test.json");
You can read about how json_decode works here, its essential we pass it the true parameter to make our arrays associative.
You can extract your need array from JSON data. You can use a loop too to read all your data inside the order array.
$array = json_decode($json, true);
$verbose = $array['data'];
$orderArray = $verbose['order'];
print_r($orderArray);
echo $orderArray['id'];
echo $orderArray['ip_address'];
Need help with the following I writing a webhook in php, and need the ability to read the context parameters.
Can someone help me to understand how it can be done?
Here is my example JSON:
{
"id": "6e774dc2-2323-42b3-bd3c-ab64930f8b92",
"timestamp": "2017-12-22T21:12:19.094Z",
"lang": "en",
"result": {
"source": "agent",
"resolvedQuery": "Yes",
"action": "Triage.Triage-yes",
"actionIncomplete": false,
"parameters": {},
"contexts": [
{
"name": "triage-followup",
"parameters": {
"triagecriteria": [],
"roomEntity.original": "",
"roomname": "300",
"roomnames.original": "living",
"roomid": "200",
"context": "",
"roomnames": [
"living"
],
"counter": "400",
"roomEntity": "100",
"triagecriteria.original": ""
},
"lifespan": 3
}
],
"metadata": {
"intentId": "ecd4a2e5-65a0-41b2-ac72-edcf4d2e73f2",
"webhookUsed": "true",
"webhookForSlotFillingUsed": "false",
"webhookResponseTime": 203,
"intentName": "Triage - yes"
},
"fulfillment": {
"speech": "Yes",
"source": "agent",
"displayText": "No",
"messages": [
{
"type": 0,
"speech": "Yes"
}
]
},
"score": 1
},
"status": {
"code": 200,
"errorType": "success",
"webhookTimedOut": false
},
"sessionId": "db8c1a4e-fa0c-4257-a536-78b63879eef9"
}
I want to be able to refer to [results][Contexts][Parameters]
I am using
$update_response = file_get_contents("php://input");
$update = json_decode($update_response, true, 512, JSON_BIGINT_AS_STRING);
and trying to access the value as $update["results"]["Contexts"]["Parameters"]["roomid"]
The names are case sensitive, and you need to be careful about trailing "s"es. Since some of the items are numerically indexed arrays, you'll need to include that as part of the index. Try
$update["result"]["contexts"][0]["parameters"]["roomid"]
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);