I am trying to write a simple demo that reads a json file with php and ajax. In js I have
// initial entry point
function main(){
var button = document.getElementById("button");
button.addEventListener("click",test);
button.addEventListener("click",getSummary);
}
function test(){
console.log("button was clicked");
}
function getSummary(){
asyncRequest = new XMLHttpRequest();
asyncRequest.addEventListener("readystatechange", processResponse, false);
console.log("sending request");
asyncRequest.open("GET","http://localhost/summary.php",true);
asyncRequest.send(null);
}
function processResponse(){
console.log("processing request");
if(asyncRequest.readyState==4 && asyncRequest.status==200){
console.log(asyncRequest.response);
}
}
summary.php
<?php
$data = readfile("summary.json");
header('Content-Type: text/json;charset=utf-8');
echo json_encode($data);
summary.json
{
"products":[
{
"product":"professional pencil",
"image":"pencil.jpg",
"description":"The most verstile tool any programmer can have. With this professional pencil you'll be able to sketch out plans and fix mistakes!"
},
{
"product":"coffee mug",
"image":"coffee_mug.jpg",
"description":"Keep your programming skills sharp and your coffee hot with this one of a kind coffee mug."
},
{
"product":"programming book",
"image":"programming_book.jpg",
"description":"Learn how to program effectively by reading this book."
}
]
}
When I make a request I get an unusual 706 at the end of the response.
curl localhost/summary.php | Select Content -Expand Content | jq produces
{
"products": [
{
"product": "professional pencil",
"image": "pencil.jpg",
"description": "The most verstile tool any programmer can have. With this professional pencil you'll be able to sketch out plans and fix mistakes!"
},
{
"product": "coffee mug",
"image": "coffee_mug.jpg",
"description": "Keep your programming skills sharp and your coffee hot with this one of a kind coffee mug."
},
{
"product": "programming book",
"image": "programming_book.jpg",
"description": "Learn how to program effectively by reading this book."
}
]
}
706
Any help with this would be greatly appreciated.
For your summary.php you actually want it to be more like the following to do what you are intending to do
<?php
$data = file_get_contents("summary.json");
header('Content-Type: text/json;charset=utf-8');
echo $data;
json_encode isn't necessary when the data is already JSON text.
And, more importantly, readFile returns a number indicating the number of bytes read. That's the number in $data which you're then outputting and seeing in your results. readFile sends the actual file data direct to the output, not into a variable.
So your code can be shortened to simply
header('Content-Type: text/json;charset=utf-8');
readfile("summary.json");
Documentation: https://www.php.net/manual/en/function.readfile.php
Related
I am trying to get a simple webhook (written in PHP) to work with dialogflow/actions on google. I have a dialog flow intent labled "hello" which is linked to the "google assistant welcome" and dialog flow "welcome" events.
it is set to enable webhook, and everything works correctly in the dialog flow test area. when i test it in google assistant, however, i get the following error:
"MalformedResponse
Failed to parse Dialogflow response into AppResponse."
I have no clue what is wrong. Here is what my JSON response looks like:
{
"payload": {
"google": {
"expectUserResponse": false,
"richResponse": {
"items": {
"simpleResponse": {
"textToSpeech": "test speech"
}
}
}
}
},
"fulfillmentText": "fulfillment test"
}
Thanks!
It works in the Dialogflow test area because that just tests the Dialogflow portion of the response. It ignores anything under the platform-specific payload area.
Your payload contains a small error. The items property of the richResponse should be an array of item objects, even if you're only sending one.
So that part of your JSON should look more like:
"richResponse": {
"items": [
{
"simpleResponse": {
"textToSpeech": "test speech"
}
}
]
}
Using php, how can I fetch specific data from dialogflow fulfillment JSON request and store the data into a php variable?
Here is the JSON response I 'm getting from my dialogflow agent
{
"responseId": "e9106589-2a41-47c4-bdde-8f3cee8f40da",
"queryResult": {
"queryText": "switch on cfl",
"action": "input.switchoncfl",
"parameters": {
"makeRequest": "cfl_on"
},
"allRequiredParamsPresent": true,
"fulfillmentMessages": [
{
"platform": "ACTIONS_ON_GOOGLE",
"simpleResponses": {
"simpleResponses": [
{
"textToSpeech": "Sure. Turning CFL on... Anything else can I help you with?",
"displayText": "Sure. Turning CFL on..."
}
]
}
}
],
"intent": {
"name": "projects/smarthome-cf277/agent/intents/5be27f38-105d-4854-b62d-ec3a6de80cc7",
"displayName": "1.1-Switch_on_CFL"
},
"intentDetectionConfidence": 1,
"languageCode": "en"
},
"originalDetectIntentRequest": {
"payload": {}
},
"session": "projects/smarthome-cf277/agent/sessions/ca0261aa-913f-96f1-b5aa-7755637d5ab7"
}
And here is my php code
<?php
header("Content-Type: application/json");
ob_start();
$content = json_decode(file_get_contents('php://input'),true);
$action = $content['parameters']['makeRequest'];
ob_end_clean();
?>
I want to store cfl_on value to $action variable. How can I do that? this php code does not work.
You just missed out the "queryResult" layer of the object.
$action = $content['queryResult']['parameters']['makeRequest'];
I'm using zoho crm..
I get the json data below returned from a query
however I'm struggling to get the value of a string inside the returned data
Here is a sample of the data returned
"response": {
"result": {
"Deals": {
"row": {
"no": "1",
"FL": [
{
"val": "DEALID",
"content": "3508588000000206039"
},
{
"val": "SMOWNERID",
"content": "3508588000000176021"
},
{
"val": "Amount",
"content": "5000"
}
I'm trying to get the Amount value
Here is the PHP code
$json = file_get_contents($url);
$obj = json_decode($json);
$amount = $obj->result->Deals->row->FL['Amount'];
echo 'Deal Amount : £'.$amount;
Thanks In Advance
You need to change a bit
$amount = $obj->response->result->Deals->row->FL[2]->content;
//--------------^index------------------------^index---^column name need to be correct---
Dealing with Zoho response could get messy. You could use this library to help smoothen things for you.
In the meantime, $obj->response->result->Deals->row->FL[2]->content; should do the trick for you.
I am working on alexa for the first time and I am developing a music app. I need to add multiple track of one artist and play it continuously. I am unable to do so. However, one song is working properly but unable to add and play multiple song.
Here is my code,
$response = '{
"version" : "1.0",
"response" : {
"outputSpeech": {
"type": "PlainText",
"text": "Playing song for Acon"
},
'.$card.',
"directives": [
{
"type": "AudioPlayer.Play",
"playBehavior": "REPLACE_ALL",
"audioItem": {
"stream": {
"token": "track1",
"url": "https://p.scdn.co/mp3-preview/9153bcc4d7bef50eb80a809fa34e694f2854e539?cid=null",
"offsetInMilliseconds": 0
}
}
}
],
"shouldEndSession" : true
}
}';
You need to wait for the AudioPlayer.PlaybackNearlyFinished request from Alexa. At that point, you can enqueue the next track to be played. It will come near the conclusion of the playback of the currently playing track.
Information on it is here:
https://developer.amazon.com/public/solutions/alexa/alexa-skills-kit/docs/custom-audioplayer-interface-reference#playbacknearlyfinished-request
When replying with a directive to PlaybackNearlyFinished, be sure that:
You set the playBehavior to ENQUEUE
This will cause the next track to start after the current one finishes
You do NOT include the outputSpeech field
outputSpeech is not allowed when out of session. The session ends when the first stream begins playback.
This blog post that I wrote goes into more detail on approaches to developing and testing for the AudioPlayer interface:
https://bespoken.tools/blog/2016/10/10/unit-testing-alexa-skills
Follow the above doc:
https://developer.amazon.com/public/solutions/alexa/alexa-skills-kit/docs/custom-audioplayer-interface-reference#playbacknearlyfinished-request
and then do this to enqueue the second song
In PHP, the way you are handling other requests, you can handle AudioRequest too. For example.
$data = file_get_contents("php://input");
$jsonData = json_decode($data);
if($jsonData->request->type === "AudioPlayer.PlaybackNearlyFinished")
{
$response = '{
"version" : "1.0",
"response" : {
"directives": [
{
"type": "AudioPlayer.Play",
"playBehavior": "ENQUEUE",
"audioItem": {
"stream": {
"token": "track2",
"expectedPreviousToken": "track1",
"url": "Your URL",
"offsetInMilliseconds": 3
}
}
}
],
"shouldEndSession" : true
}
}';
echo $response;
}
This is the way you can handle all the AudioRequest.
I'm trying to use Tumblrs API and when I visit the URL for the API I get this below
{
"meta": {
"status": 200
"msg": "OK",
},
"response": {
"blog": {
"title": "Ex-Sample",
"posts": 20,
"name": "example",
"url": "http://example.tumblr.com/",
"updated": 1327794725,
"description": "A sample document used to provide examples of the various [and <i>varying</i>] HTML tags Tumblr puts out. Quote, specifically, has a lot of variants.",
"ask": false
}
}
}
The URL is http://api.tumblr.com/v2/blog/example.tumblr.com/info?api_key=(APIKEY)
I'm trying to get what the "post" number is with that URL above. How would I do that in PHP and echo the number only out?.
That looks like a JSON string, so...
$msg = '{"meta" etc.....';
$data = json_decode($msg);
echo $data['meta']['response']['blog']['posts'];
You can use
var_dump($data);
to dump the entire response in a nicely formatted tree structure.