Get value from nested json php - php

I am receiving data from a webhook with the following code below.
<?php
$inputJSON = file_get_contents('php://input');
$input = json_decode($inputJSON, TRUE);
$myfile = fopen("callback.txt", "a") or die("Unable to open file!");
$txt = $input["payload"]["type"];
fwrite($myfile, "\n". $txt);
fclose($myfile);
http_response_code(200);
?>
I am trying to get the 'type' value from the retuned output. I have found that using an if statement inside a for each loop would do the job. However i'm sure this isn't an ideal solution. is there a more direct way of getting that element?
The code above is outputting an empty text file.
and the documentation shows the json should be in the following format:
{
"action": "add",
"collection": "broadcast",
"payload": {
"author": "Sveninge Bambuser",
"created": 1474033783,
"customData": "",
"height": 540,
"id": "9353eaec-794f-11e6-97c0-f19001529702",
"ingestChannel": "cfc8626c-9a0e-ab78-6424-3eb0978d8e45",
"lat": 63.205312,
"length": 0,
"lon": 17.13011,
"positionAccuracy": 25,
"positionType": "GPS",
"preview": "https://archive.bambuser.com/9353eaec-794f-11e6-97c0-f19001529702.jpg",
"resourceUri": "https://cdn.bambuser.net/broadcasts/9353eaec-794f-11e6-97c0-f19001529702?da_signature_method=HMAC-SHA256&da_id=9353eaec-794f-11e6-97c0-f19001529702&da_timestamp=1474033783&da_static=1&da_ttl=0&da_signature=eaf4c9cb29c58b910dcbad17cf7d8a3afa4e6a963624ba4c4fd0bb5bade1cdd6",
"tags": [
{
"text": "whoa"
}
],
"title": "Amazing!",
"type": "live",
"width": 960
},
"eventId": "93df93061a891c23"
}

I replaced:
$txt = $input["payload"]["type"];
with:
$txt = $input['payload']['type'];
it appears to be the double quotes causing the issue.

Related

PHP fails to parse JSON - Unexpected Integer

I'm trying to make an application that will use a JSON input. Below is some code that shows the problem when run. The problem being a syntax error; unexpected integer from the "etag" line ("$etag": "W/\"datetime'2019-10-31T23%3A22%3A09.7835369Z'\"",). When I remove the etag line it runs fine but otherwise I get an error. Can I remove the etag line (not needed anyway) before being parsed or get around it some other way? I unfortunately cant change what the API sends.
<?php
$json = '{
"Form": {
"Id": "1",
"InternalName": "SignUp",
"Name": "Sign Up"
},
"$version": 7,
"$etag": "W/\"datetime'2019-10-31T23%3A22%3A09.7835369Z'\"",
"Email": "test#email.com",
"Phone": "(123) 412-3412",
"CarrierServiceProvider": "Sprint",
"WTSKeywords": "Testing WTS",
"WTBKeywords": "Testing WTB",
"Id": "1-3",
"Email_IsRequired": false,
"Phone_IsRequired": false,
"CarrierServiceProvider_IsRequired": true
}';
$data = json_decode($json);
echo $data->Email;
echo "\n";
echo $data->WTBKeywords;
?>
Code should output: test#email.com Testing WTB
You json string has both ' and ", so you cannot simple use single or double quoted.
Use heredoc like this,
$json = <<<EOT
{
"Form": {
"Id": "1",
"InternalName": "SignUp",
"Name": "Sign Up"
},
"$version": 7,
"$etag": "W/\"datetime'2019-10-31T23%3A22%3A09.7835369Z'\"",
"Email": "test#email.com",
"Phone": "(123) 412-3412",
"CarrierServiceProvider": "Sprint",
"WTSKeywords": "Testing WTS",
"WTBKeywords": "Testing WTB",
"Id": "1-3",
"Email_IsRequired": false,
"Phone_IsRequired": false,
"CarrierServiceProvider_IsRequired": true
}
EOT;
$data = json_decode($json);
echo $data->Email;
echo "\n";
echo $data->WTBKeywords;

PHP 7.2 json_decode()

I have this string that was working with json_decode() with PHP 5.6 but doesn't work with PHP 7.2?
$json = '
{
"text": "Hi {{fname}}
Welcome to our customer support.
Please select language to proceed",
"buttons": [
{
"text": "English",
"value": "language_english",
"type": "postback"
},
{
"text": "Germany",
"value": "language_germany",
"type": "postback"
}
]
}';
I have tried replacing the whitespaces and newline like this
$json = preg_replace("/\n/m", '\n', $json);
$what = "\\x00-\\x19"; // all whitespace characters except space itself
$json = trim(preg_replace( "/[".$what."]+/" , '' , $json));
Which results into a string like this
\n{\n "text": "Hi {{fname}} \n Welcome to our customer support. \n Please select language to proceed",\n "buttons": [\n {\n "text": "English",\n "value": "language_english",\n "type": "postback"\n },\n {\n "text": "Germany",\n "value": "language_germany",\n "type": "postback"\n }\n ]\n}
Notice the \n in between and outside double quotes which makes it an invalid json and hence json_decode won't work in this case.
Does anyone know a way to achieve this?
Thank you.
{
"text": "Hi {{fname}} \n Welcome to our customer support. \n Please select language to proceed",
"buttons": [{
"text": "English",
"value": "language_english",
"type": "postback"
},
{
"text": "Germany",
"value": "language_germany",
"type": "postback"
}
]
}
This is a valid json. i added line breaks so you can use them if you want to print the messages in browser.
You can use this nice tool to validate your json when you have doubts.
Editing my answer based on comment feedback.
First of all the right step is that you figure out why you have a broken json in the database. If it's not on you and you have to fix it in php then a solution could be like this:
<?php
echo '<pre>';
$data = '
{
"text": "Hi {{fname}}
Welcome to our customer support.
Please select language to proceed",
"buttons": [
{
"text": "English",
"value": "language_english",
"type": "postback"
},
{
"text": "Germany",
"value": "language_germany",
"type": "postback"
}
]
}';
if (strstr($data, "\n")) {
$data = trim(preg_replace('/\s\s+/', ' ', $data));
}
echo $data;
Above code will capture the line breaks of your text field, and replace them with DOUBLE space. Then you will get a valid json like:
{
"text": "Hi {{fname}} Welcome to our customer support. Please select language to proceed",
"buttons": [
{
"text": "English",
"value": "language_english",
"type": "postback"
},
{
"text": "Germany",
"value": "language_germany",
"type": "postback"
}
]
}
What you can do if you need the line breaks is that you decode your json (just like you want and replace the double spacing in text field with a line break

Getting data from json and passing to url

Want to send the json data to my url, when the json is received i receive all the json data on the url and not the data from 'resolvedQuery'
$update_response = file_get_contents("php://input");
$update = json_decode($update_response, true);
$results = $update['result']['resolvedQuery'];
$url = "https://autoremotejoaomgcd.appspot.com/sendmessage?key=APA91bEq&message=Data" . urlencode(json_encode($update));
Json Data
{
"id": "4ed272a3-b9a4-4f18-a67e-10e12e4f4149",
"timestamp": "2017-12-10T10:07:54.282Z",
"lang": "en",
"result": {
"source": "agent",
"resolvedQuery": "turn livingroom light on",
"action": "",
"actionIncomplete": false,
"parameters": {
"power-toggle": "on",
"room": "livingroom"
},
"contexts": [],
"metadata": {
"intentId": "19764ecc-715c-4b25-960f-9845f2aef1f9",
"webhookUsed": "true",
"webhookForSlotFillingUsed": "false",
"webhookResponseTime": 503,
"intentName": "lights"
},
"fulfillment": {
"speech": "Ok, Turning livingroom light on",
"messages": [
{
"type": 0,
"speech": "Ok, Turning livingroom light on"
}
]
},
"score": 1
},
"status": {
"code": 206,
"errorType": "partial_content",
"errorDetails": "Webhook call failed. Error: Webhook response was empty.",
"webhookTimedOut": false
},
"sessionId": "395d3517-05da-42ac-9037-dadac519ab0b"
}
How do i get data from 'resolvedQuery' and send it to my URL
In the code you provided, you have the following line of code
$url = "https://autoremotejoaomgcd.appspot.com/sendmessage?key=APA91bEq&message=Data"
. urlencode(json_encode($update));
You are appending to the URL parameter message the results of json_decode($update_response, true). $update_response contains all the decoded JSON data posted by the HTTP request which is not what you want.
I believe what you want is a new parameter called resolved-query to be set to the results of json_decode($result, true).
Try chaninging your $url variable to the following:
$url = "https://autoremotejoaomgcd.appspot.com/sendmessage?key=APA91bEq&message=Data&resolved-query="
. urlencode(json_encode($result));
URL will be set to the following string:
https://autoremotejoaomgcd.appspot.com/sendmessage?
key=APA91bEq&
message=Data&
resolved-query=turn+livingroom+light+on

json_decode doesn't work on my string

I have JSON Object which I have encoded like so
{
"id": "",
"steps": [
{
"target": "purchase_order_items_itemmaster_id",
"title": "",
"placement": "",
"content": "",
"xoffset": "",
"yoffset": ""
}
]
}
$JSONData = json_encode($finalData,JSON_PRETTY_PRINT);
I am taking this JSON data and storing it in a file like so
File::put("path","var tour = \n [ \n\t $JSONData \n ];");
which looks something like this in the file
var tour =
[
{
"id": "",
"steps": [
{
"target": "purchase_order_items_itemmaster_id",
"title": "",
"placement": "",
"content": "",
"xoffset": "",
"yoffset": ""
}
]
}
];
Now I am reading it back form the second line like so
[
{
"id": "",
"steps": [
{
"target": "purchase_order_items_itemmaster_id",
"title": "",
"placement": "",
"content": "",
"xoffset": "",
"yoffset": ""
}
]
}
];
The problem is when I want to decode it back it doesn't happen,this is how I am trying to do that,
$lines = file_get_contents("path",NULL,NULL,10);
$a = json_decode($lines);
Now according to expected output the $a should have the decoded data but it has null.
Can someone point out the mistake?
I believe the issue is the semicolon at the end of the JSON you've read back in from the file. Try chopping that off before attempting json_decode:
$a = json_decode(rtrim($lines, ";"));
pass the second parameter true for recursively decoding
$a = json_decode(chop($lines,";"),true);
check the php mannual here json_decode
It will be
$str = file_get_contents('http://example.com/example.json/');
$json = json_decode($str, true); // decode the JSON into an associative array
See the post
Parsing JSON file with PHP
try to save data in file like
$fp = fopen('path', 'w');
fwrite($fp, json_encode($JSONData)); //if $JSONData is in string
fclose($fp);
instead of
File::put("path","var tour = \n [ \n\t $JSONData \n ];");
//and read like
// Read JSON file
$json = file_get_contents('path');
//Decode JSON
$json_data = json_decode($json,true);
//Print data
print_r($json_data);

JSON Not Working on PHP Script

I got 2 JSON files extracted from the same db,
a:)
{
"hint_data": {
"locations": ["AXQDAP____8AAAAABwAAABEAAAAYAAAAIwIAAERwAgAAAAAADgyCAef7TAMCAAEB", "bOsDAP____8AAAAAAwAAAAcAAADFAQAAFAAAAEJwAgAAAAAANQeCAdzdTAMFAAEB"],
"checksum": 326195011
},
"route_name": ["", ""],
"via_indices": [0, 15],
"via_points": [
[25.299982, 55.376873],
[25.29874, 55.369179]
],
"found_alternative": false,
"route_summary": {
"end_point": "",
"start_point": "",
"total_time": 101,
"total_distance": 871
},
"route_geometry": "{_ego#m}|rhBpBaBvHuC`EuArEUtEtAlDvEnD`MlDvMli#hsEfFzn#QlTgNhwCs#fKwBjF",
"status_message": "Found route between points",
"status": 0
}
b:)
{
"alternative_names": [
["", ""]
],
"route_name": ["", ""],
"status_message": "Found route between points",
"route_geometry": "qo{o#wpslhBmFZwEpBgDzDeBlFWdGv#GCzEyBfIyEtEoNtEuMpAuHkAsCgC[mB{AgCuA{#uCa#}Cl#yBtB}#lDVhEcAtDmCdBcDx#iDDeDk#uBeBeB_CcGcXyFi^{Dg\\wBkP_Fs^wBiS_Ce[_D}UwAcKiBqIgI_TeLaUcMmP_IsHqf#_WyJeE}FMkDjIiTth#y|#loBq^vy#mu#fw#cUxOco#r^gb#zRoOjPsBfMq#rMjBdPnEpKlEnHJ~Dvn#la#nd#pT|f#lLv_#pRzLbHnb#fUxc#lMnaC~zAncBxnAkB|bB|CbmCl]rYxCzkCjwBzoBjxGl_G|fNhcMf~E~mE~pFt}EjbBlzAhvInyHfqDb~CblAw#poAzt#z}#bb#diD~dBxtEjgCfjDljBpuAfw#bpGngDhqF~yC~g#la#v~#ni#rbAjg#jPJlCFNdDGdDu#j#eAhBa#lCLdCaCjI_BtCy#vA_DvF}qAf}Bof#l{#{CnFoKdR}mAxBgM|TkJxPmLlSsf#|}#gf#x#kOzXmEfGmSx^kf#tw#mDtL}k#r~#ykCjjEau#niAee#bu#uUl\\}DpFzCrCr|#dt#|NbLroBx_BdZlV|DbDpBr~Anq#xm#r|#ls#|y#dq#}OXuMQcDhEoBgBeCCu[xXmBH",
"route_summary": {
"end_point": "",
"start_point": "",
"total_time": 824,
"total_distance": 15391
},
"found_alternative": true,
"alternative_summaries": [{
"end_point": "",
"start_point": "",
"total_time": 886,
"total_distance": 14967
}],
"via_points": [
[25.196808, 55.273754],
[25.139168, 55.187702]
],
"status": 0,
"via_indices": [0, 144],
"hint_data": {
"locations": ["TdMLAP____8AAAAADwAAAA8AAAA9AAAAbAAAAOtwBgAAAAAACXmAARxpSwMEAAEB", "4Q4AAGKyBgAAAAAACQAAAAAAAAAhAQAAAAAAAGUYAAAAAAAA4Zd_AfgYSgMGAAEB"],
"checksum": 326195011
},
"alternative_geometries": ["qo{o#wpslhBmFZwEpBgDzDeBlFWdGv#GCzEyBfIyEtEoNtEuMpAuHkAsCgC[mB{AgCuA{#uCa#}Cl#yBtB}#lDVhEcAtDmCdBcDx#iDDeDk#uBeBeB_CcGcXyFi^{Dg\\wBkP_Fs^wBiS_Ce[_D}UwAcKiBqIgI_TeLaUcMmP_IsHqf#_WyJeE}FMkDjIiTth#y|#loBq^vy#ec#vfAyeAfcCok#vtA}Wtx#uS|d#skAvfCgExJgJpTqH|O}#n~#wSve#qEhKkYdp#gB~DuUrk#_JdRsAhDmJlVqd#rcAuM|Zeg#zkAiKzUgIbS}B~EtDvBhr#a#dQ~J|rBpmAj_CfyAlAzD^lDgHnOyQlg#w[l|#}Q~d#eBB}Af#mAdAw#bBWpBJrBn#hBaAjGif#ptAk^rmAoVxy#cHjPmCHE|Bp[xRpc#ZfLvIzLlIreG~cEjrArz#rmAl|#lbDrzBjWlQ|xA~bAho#pc#d_#jWng#j^hNzJvGnEnPjLlAx#lgAhv#bGvCjkBvoAbjDr}BvfAx{#t\\rSfoDviC~zAjgAfOxIvAbAjwCtsBv|#|m#bD|BvLId_Dt|BtLlIxsAx_AfE~Crn#hc#rKvIh_BniApe#z\xIpGtoBpxAtEdDrQrMzjChlB~#lo#nwFpE|jBl|AzFzE|DfDvDrCjKfJr#n\\pLzKnBzzAdO~LhaFxaEzCdCnLpKbp#ti#nIjHdRzMjo#tg#~MvKpwCtdClw#bm#z[bWfr#vk#zCrCr|#dt#|NbLroBx_BdZlV|DbDpBr~Anq#xm#r|#ls#|y#dq#}OXuM`QcDhEoBgBeCCu[xXmBH"],
"alternative_indices": [0, 183]
}
And I am running this script on every JSON file.
Here is the script.
<?php
$json = '{"hint_data":{"locations":["AXQDAP____8AAAAABwAAABEAAAAYAAAAIwIAAERwAgAAAAAADgyCAef7TAMCAAEB","bOsDAP____8AAAAAAwAAAAcAAADFAQAAFAAAAEJwAgAAAAAANQeCAdzdTAMFAAEB"],"checksum":326195011},"route_name":["",""],"via_indices":[0,15],"via_points":[[25.299982,55.376873],[25.29874,55.369179]],"found_alternative":false,"route_summary":{"end_point":"","start_point":"","total_time":101,"total_distance":871},"route_geometry":"{_ego#m}|rhBpBaBvHuC`EuArEUtEtAlDvEnD`MlDvMli#hsEfFzn#QlTgNhwCs#fKwBjF","status_message":"Found route between points","status":0}';
$data = json_decode($json);
$totalTime = $data->route_summary->total_time;
var_dump($totalTime); // DUMPS 101
I am getting the first JSON file output correctly but I am getting an error in the 2nd one.
Please tell me what's wrong with the JSON file.
Your json is not valid.
The "alternative_geometries" property contains a string that is not properly encoded. (\x is not valid. If you want the slash, then it would need to be \\x)
Try validating it somewhere like this: http://jsonlint.com/
1) put data to text file
2) try again with:
<?php
$data = file_get_contents('./relative/path/to/file.json');
$data = json_decode($data);
$totalTime = $data->route_summary->total_time;
var_dump($totalTime);
it would be better to write data to files and put somewhere to download them to check the file.

Categories