Sending a php array as a dialogflow response - php

Hey I am building a chatbot using dialogflow and I am generating the responses by using a customized Webhook (I am programming in php). I am extracting data from my database and storing it in an array but when I send the array as a response to dialogflow it only shows the first row.
Here is my code:
<?php
header('Content-Type: text/html; charset=utf-8');
date_default_timezone_set("Asia/Bangkok");
$date = date("Y-m-d");
$time = date("H:i:s");
$json = file_get_contents('php://input');
$request = json_decode($json, true);
$input = fopen("log_json.txt", "w") or die("Unable to open file!");
fwrite($input,$json);
fclose($input);
function processMessage($update) {
if($update["queryResult"]["action"] == "ques"){
$bdd= new PDO('mysql:host=localhost;dbname=****', '****', '***', array(
PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8")) ;
$data = array();
$nom= $update["queryResult"]["parameters"]["nom_aliment"];
$info=$update["queryResult"]["parameters"]["Information"];
$quantite=$update["queryResult"]["parameters"]["Quantite"];
$req=$bdd->prepare("SELECT * FROM TableCiqual WHERE alim_nom LIKE ? ");
$req->execute(array("%$nom%"));
while($resultat=$req->fetch()){
$variab=$resultat[$info]*$quantite/100;
$ppp =$resultat['alim_nom'].' '.$info.' : '.$variab;
$data=$ppp;
}
sendMessage(array(
"source" => $update["responseId"],
"fulfillmentText"=>$data,
"payload" => array(
"items"=>[
array(
"simpleResponse"=>
array(
"textToSpeech"=>"Bad request"
)
)
],
),
));
}
}
function sendMessage($parameters) {
echo json_encode($parameters);
}
I know that my query returns multiple results all these results are stored in the array $data that I send as a response in dialogflow. The problem is that dialogflow only shows me the first row of the array $data instead of the whole array with all the rows.
My question is : Is it possible to send an array as a response in dialogflow and if yes how so.

I think there are two issues here.
The first is that $data is not actually containing a list of your results. The line
$data = $ppp;
is assigning $ppp, which is a string, to $data rather than adding on to the end of the array. I think, for that line, you want something more like
$data[] = $ppp;
However, this doesn't solve your problem completely, since the fulfillmentText attribute in JSON isn't expecting an array - it is expecting a string. So you probably want to concatenate all of those entries with something like
"filfillmentText" => implode( "\n", $data );
However, this assumes that you both want a new line in between each answer and that the chat system you're using supports the feature this way - not all do. (And you haven't indicated which one you're using.)

Related

Returning an array from PHP to jQuery from Ajax

I'm trying to get PHP returned array from Ajax.
Here is my Ajax call:
And my PHP code is this:
Query is running perfectly.
I have tried to get values like alert(data[0].program_title) in ajax success. But it also returns Undefined.
How can I fix this issue?
In your PHP code:
//remove
return $data
//change with
echo json_encode($data);
Just before flushing the data back to the stream (returning), convert your data ($data variable in this case) to JSON string using json_encode and add the proper content-type application/json using header function.
However, the best practice is to provide some metadata to your data included in your transfer, like the size of data and count of elements in data and if paginated, which page the data refers to and what the maximum available pages and maximum element size of a page are.
Here's a sample body structure for a more robust data transfer:
$response = [
'page' => 0, // e.g.
'count' => count($data),
'data' => $data,
'max_page' => 3, // e.g.
'item_per_page' => 15, // e.g.
'status_code' => 200, // e.g.
];
header ( "Content-Type: application\/json", true , 200);
return json_encode(
$response
, JSON_INVALID_UTF8_SUBSTITUTE
| JSON_NUMERIC_CHECK
| JSON_PRESERVE_ZERO_FRACTION
| JSON_UNESCAPED_LINE_TERMINATORS
| JSON_UNESCAPED_SLASHES
| JSON_UNESCAPED_UNICODE
);
Try this:
$data = [];
if ($numRows>0) {
while($row=$result->fetch_assoc()) {
$data[] = $row;
}
}
Replace return with echo and add json_encode
echo json_encode($data);

Can't display more than one item from amazon product api response

I'm fetching top selling items for a particular browseNodeId. The xml response has 10 items but when I print/display the information it shows only one. Please help.
My request array is:
$params = array(
"Service" => "AWSECommerceService",
"Operation" => "BrowseNodeLookup",
"AWSAccessKeyId" => "",
"AssociateTag" => "",
"BrowseNodeId" => "6386372011",
"ResponseGroup" => "TopSellers"
);
(I removed my ids on purpose)
and this is how I'm parsing xml response:
$response = simplexml_load_file($request_url);
foreach($response->BrowseNodes->BrowseNode as $item)
{
$topItem = $item->TopItemSet->TopItem->Title;
$itemURL = $item->TopItemSet->TopItem->DetailPageURL;
$itemID = $item->TopItemSet->TopItem->ASIN;
$results .= "<tr><td>$topItem</td><td>$itemID</td></tr>";
}
later on I'm simply printing '$results' using echo command. This approach is working with all other requesting/responses i.e. I'm getting & displaying 10 items without any problem. I can't find any error. Please help, I want to display 10 items not just one.
Convert the XML Object into array using this
$response = simplexml_load_file($request_url);
$json_string = json_encode($response);
$result = json_decode($json_string, TRUE);
And then access the elements using array['key'] syntax.

PHP Processing stream_get_contents into an array

I am having troubles converting a string which contains tab delimited CSV output
into an array. While using the following code :
$data = stream_get_contents($request->getShipmentReport());
I get back data as following:
Date Shipped Comments Feedback Arrived on Time
5/11/15 2 comment response Yes
Now I would like to process this data into an array with the returned headers(line 1) as the index containing the value for each line which follows after that.
I am trying to end up with something like this :
$line['Date'] = 5/11/15
$line['Shipped'] = 2
$line['Feedback'] = response
$line['Arrived on Time'] yes
What would be the best way to achieve this ?
I recommend using a library for handling CSV for example the CSV-Package by The League of Extraordinary Packages
You can pass your data and start working with array structures right away:
$csvString = stream_get_contents($request->getShipmentReport());
$csvReader = \League\Csv\Reader::createFromString($csvString);
$data = $csvReader->fetchAssoc(
array('Date', 'Shipped', 'Comments', 'Feedback', 'Arrived on Time')
);
// Or since line 0 contains header
$data = $csvReader->fetchAssoc(0); // 0 is offset of dataset containing keys
Now your data should be in a structure like:
$data = array(
array(
'Date' => '5/11/15',
'Shipped' => '2',
...
),
array(
...
)
);
You can even filter out specific datasets and all kinds of fancy stuff. Just check the documentation I linked to.
League CSV reader gives me a bad result. I use this instead:
$csvReportString = stream_get_contents($request->getReport());
$csvReportRows = explode("\n", $csvReportString);
$report = [];
foreach ($csvReportRows as $c) {
var_dump($c);
if ($c) { $report[] = str_getcsv($c, "\t");}
}
var_dump($report);

Echoing an array using json_encode

Using a javascript application I am making a server side request for a search functionality. It works for some queries, but not for others.
For some queries the GET request returns no response, despite the fact that testing the query in workbench returns thousands of records. I tried turning on errors - no errors are generated. I tried increasing memory limit - that's not the culprit. I tried to output PDO errors/warnings - nothing generated, the PDO actually returns the records, I verified this using var_dump, as shown below.
So to conclude, everything in the below code, seems to work flawlessly, until the final line that is responsible for encoding the array into a json object - it echos nothing.
I appreciate any assistance in resolving this.
PHP
error_reporting(E_ALL);
ini_set('display_errors', 1);
ini_set('memory_limit', '2048M');
$db = new PDO('mysql:host=localhost;dbname=mydb', 'root', '');
$search = $_GET['search'];
$searchBy = ( isset($_GET['searchBy']) && !empty($_GET['searchBy']) ) ? $_GET['searchBy'] : 'name';
$sql = "SELECT * FROM business WHERE name LIKE '%university%' GROUP BY id";
$query = $db->prepare($sql);
$query->execute();
$results = $query->fetchAll(); //query returns 5000+ records in under a second in workbench
$headers = array('Business', 'City', 'State', 'Zip', 'Phone');
$json = array("results" => $results, 'headers' => $headers, 'query' => $sql);
var_dump($json); //prints successfully
echo json_encode($json); // echos nothing!
EDIT:
use utf8_encode() then json_encode() as mentioned here (Special apostrophe breaks JSON)
OR
$dbHandle = new PDO("mysql:host=$dbHost;dbname=$dbName;charset=utf8", $dbUser, $dbPass,array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'utf8'"));
will parse all the data in utf8.
Old
What's the result if you do this ?
echo json_encode($results);
//scratch those
//$json = array("results" => $results, 'headers' => $headers, 'query' => $sql);
//var_dump($json); //prints successfully
May be you run out of memory? Try with a 100 results. I know from experience with other projects that json_encode can consume a shared server's ram.
Sorry if I am not as helpful as you would like me to be but we can't really test you code, you have to do it for us.
I had this exact error when I tried to use json_encode the other day. It returned no errors... just a blank screen, and finally it hit me. The issues was with character encoding. The column I was trying to use had been used by copywriters who cut and pasted from Microsoft Word directly into the wysiwyg.
echo json_last_error() after your json_encode and see what you get
.
.
.
echo json_encode($json); // echos nothing!
echo json_last_error(); // integer if error hopefully 0
It should return an integer specifying one of the errors below.
0 = JSON_ERROR_NONE
1 = JSON_ERROR_DEPTH
2 = JSON_ERROR_STATE_MISMATCH
3 = JSON_ERROR_CTRL_CHAR
4 = JSON_ERROR_SYNTAX
5 = JSON_ERROR_UTF8
In my case it returned a 5. I then had to clean every "description" column before it would work. In the event it is the same error, I've included the function you will need to run all your columns through to clean them out.
function utf8Clean($string)
{
//reject overly long 2 byte sequences, as well as characters above U+10000 and replace with *
$string = preg_replace('/[\x00-\x08\x10\x0B\x0C\x0E-\x19\x7F]'.
'|[\x00-\x7F][\x80-\xBF]+'.
'|([\xC0\xC1]|[\xF0-\xFF])[\x80-\xBF]*'.
'|[\xC2-\xDF]((?![\x80-\xBF])|[\x80-\xBF]{2,})'.
'|[\xE0-\xEF](([\x80-\xBF](?![\x80-\xBF]))|(?![\x80-\xBF]{2})|[\x80-\xBF]{3,})/S',
'*', $string );
//reject overly long 3 byte sequences and UTF-16 surrogates and replace with ?
$string = preg_replace('/\xE0[\x80-\x9F][\x80-\xBF]'.
'|\xED[\xA0-\xBF][\x80-\xBF]/S','?', $string );
return $string;
}
for more info on json_last_error() go to the source!
http://php.net/manual/en/function.json-last-error.php
It is really easy with the JSON Builder : Simple JSON for PHP
include('includes/json.php');
$Json = new json();
$Json->add('status', '200');
$Json->add('message', 'Success');
$Json->add('query', 'sql');
$Json->add("headers",$headers);
$Json->add("data",$results);
$Json->send();

Create duplicate tags on NuSOAP

I'm having some troubles with NuSOAP trying to send duplicate tags. This is the code i need to send :
<PartNumbers>
<string>string1</string>
<string>string2</string>
</PartNumbers>
I'm doing the call with this code:
$pn[] = 'APPSP2101V2';
$pn[] = 'ME665Y/A';
$PartNumbers = array( 'PartNumbers' => array('string' => $pn));
$result = $client->call('GetDataSheetsLastUpdate', $PartNumbers );
I'm sending those two PartNumbers but instead of send the two codes it's sending the last one "ME665Y/A"
Also if i try
$PartNumbers = array( 'PartNumbers' => array('string' => 'APPSP2101V2', 'string' => 'ME665Y/A'));
$result = $client->call('GetDataSheetsLastUpdate', $PartNumbers );
Only send the last string.
How can i make an array with the same keys but different value to make the XML look like in the beggining of the question.
Thank you in advance to all
With the following code:
$pn[] = 'APPSP2101V2';
$pn[] = 'ME665Y/A';
$PartNumbers = array( 'PartNumbers' => array('string' => $pn));
$result = $client->call('GetDataSheetsLastUpdate', $PartNumbers );
Works perfect , the problema was in the webservice.. if the P/N isn't correct only return the P/N with information on it.

Categories