Parse Push Notification - PHP API - php

Parse Push Notifications are working. The thing is that I am trying to send a multiline notification and the PHP API is not detecting my EOL command. The messages arrived exactly as I send them:
Line1\r\nLine2
Any help will be appreciated.
Many thanks.
EDIT
This is my code:
require 'autoload.php';
$app_id = "zzzzzzzzzzzzzzzzzzzzzzzzz";
$rest_key = "xxxxxxxxxxxxxxxxxxxxxxxxxxxx";
$master_key = "cccccccccccccccccccccccccccccccc";
\Parse\ParseClient::initialize( $app_id, $rest_key, $master_key );
use Parse\ParsePush;
$data = array("alert" => $_POST["txtMessage"]);
ParsePush::send(array("channels" => ["Test"], "data" => $data));
EDIT #2:
My data array:
array(1) (
[alert] => (string) Line1\r\nLine2
)

It looks like you are escaping your string somewhere along the way.
This is how the escaped string will look like in PHP:
var_dump("Line1\\r\\nLine2");
string(14) "Line1\r\nLine2"
Simply because you escaped the escape character.
What you need is this:
var_dump("Line1\r\nLine2");
string(12) "Line1
Line2"
The above code should produce what you need. Check other parts of your code (also the frontend part) if there is anything that is escaping the string.

Related

Sending a php array as a dialogflow response

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.)

Issue with accents and encoding with Bing Spell Check API v7

So I am trying to work with Bing's Spell Check API in PHP, but I'm having an issues where accents and other special characters aren't decoded properly, creating many errors that aren't in the original text and messing with the offsets.
My implementation is quite simple - it's heavily based on the example they give in their documentation. I'm not sure if I am supposed to be doing something differently or if it is an issue on their side with how they decode those special characters (which seems highly unlikely - me messing something up is much more probable..!)
Here's the code:
$host = 'https://api.cognitive.microsoft.com';
$path = '/bing/v7.0/spellcheck?';
$data = array (
'mkt' => $lang,
'mode' => 'proof',
'text' => urlencode($text)
);
$encodedData = http_build_query($data);
$key = 'subscription key redacted for obvious reasons';
$headers = "Content-type: application/x-www-form-urlencoded\r\n" .
"Ocp-Apim-Subscription-Key: $key\r\n";
if (isset($_SERVER['REMOTE_ADDR']))
$headers .= "X-MSEdge-ClientIP: " . $_SERVER['REMOTE_ADDR'] . "\r\n";
$options = array (
'http' => array (
'header' => $headers,
'method' => 'POST',
'content' => $encodedData
)
);
$context = stream_context_create ($options);
$result = file_get_contents ($host . $path, false, $context);
if ($result === FALSE) {
# Handle error
}
$decodedResult = json_decode($result, true);
If, for example, I try to spell check the following string:
d'institution
$encodedData becomes the following:
mkt=fr-CA&method=proof&text=d%25E2%2580%2599institutions
And the results I get from the API are the following:
array(2) {
["_type"]=>
string(10) "SpellCheck"
["flaggedTokens"]=>
array(1) {
[0]=>
array(4) {
["offset"]=>
int(8)
["token"]=>
string(14) "99institutions"
["type"]=>
string(12) "UnknownToken"
["suggestions"]=>
array(2) {
[0]=>
array(2) {
["suggestion"]=>
string(15) "99 institutions"
["score"]=>
float(0.93191315174102)
}
[1]=>
array(2) {
["suggestion"]=>
string(14) "99 institution"
["score"]=>
float(0.6518044080768)
}
}
}
}
}
As you can see, the decoding seems to be problematic, as the % gets encoded twice, and is only decoded once apparently. Now, if I remove the url_encode() when setting the value of 'text' in $data, it'll work fine for the apostrophe, but it doesn't work with accents. For example, the following string:
Responsabilité
is interpreted by the API as
Responsabilité
which returns an error.
This could very well be something simple that I'm overlooking, but I've been struggling with this for quite a while and would appreciate any help I can get.
Thanks,
- Émile
[ Edit ] Well, as always... when in doubt, assume you're wrong. The API recommended to change all of the accents for regular letters because even if the specified language was French, it still gave suggestions in English instead of returning an empty array. As for the accents that didn't seem to be decoded, well... I was var_dump-ing that data without any doctype set, so of course it would show without the proper encoding. Sorry about that - in the end, simply removing the urlencode() does the trick!
As per the docs:
The API supports two proofing modes, Proof and Spell. The default mode is Proof. The Proof spelling mode provides the most comprehensive checks, but it's available only in the en-US (English-United States) market. For all other markets, set the mode query parameter to Spell. The Spell mode finds most spelling mistakes but doesn't find some of the grammar errors that Proof catches (for example, capitalization and repeated words).

How can I get base64 to display as a base64 string in PHP?

I have been working with an API that uses tokens for authentication. I am using PHP's SoapClient class to login to said API and retrieve the tokens I need to make additional requests..
The problem is that the API should return base64 string tokens, but in PHP, they are not being dealt with as bas64 strings.. I get a string that looks like this:
ç$P%’™‹2E‡ºË>Šo_ÑÒúé±N5Tá#=œã
Instead of a base64 string that looks like this:
ERy/R5ycTG0sbRyH9KeMGpi9kPr6kROyaarFYgsPEOU=
Note: These 2 strings are not actually related, as I could not get php to display the base64 representation of that 1st string. The base64 string I listed as the 2nd string came from a valid soapUI response.
So I have confirmed with soapUI, that I the tokens do in fact come over as base64 strings, but I cannot get PHP to use them as strings for additional requests. I have tried doing base64_decode and base64_encode on the strings, along with a bunch of other encodings/decodings, but none of them have worked so far.
Any ideas as to what is going on here, and how I might be able to use the data the way I need?
Edit: Here is the code I use to get the token data. It's the DAT api if that helps.
$wsdlDat = "http://someurl.com:8000/wsdl/someWSDL.wsdl";
$soapOptions = array( 'loginId' => $userName, 'password' => $userPassword, 'thirdPartyId' => 'KEFKA_TMS', 'trace' => 1 );
$this->datClient = new SoapClient( $wsdlDat , $soapOptions );
$creds = array( 'loginId' => $userName, 'password' => $userPassword, 'thirdPartyId' => 'KEFKA_TMS' );
$loginOptions['loginOperation'] = $creds;
$this->token = $this->datClient->Login($loginOptions);
$this->token = datObjectToArray($this->token); // TURN STD CLASS OBJ TO ARRAY
$token = $this->token['loginResult']['loginSuccessData']['token']['primary'];
$token2 = $this->token['loginResult']['loginSuccessData']['token']['secondary'];
$exp = $this->token['loginResult']['loginSuccessData']['expiration'];

Receive array of numbers in php (JSON)

I would like to get an array from my JSON in php.
This way I get the JSON string from URL in my android application:
JSONObject json = jParser.makeHttpRequest(url_all_user, "GET", paramstodb);
To receive [phone=123] in php I use this:
if (isset($_GET["phone"])) {
$phone = $_GET['phone'];
That is working for one phonenumber, but now I need more than one phonenumber.
The data in Logcat (reported with "Log.d("to php: ", paramstodb.toString())" ) is displayed as:
to php:﹕ [phone=[0127361744, 0132782422, 0137173813, 0142534646, 0123617637435, 013391339494, 01383375633, 013878942423, 013891748422, 01389487285, 014434354234, 01848481371, 018831789414, 021238133441231, 021371689411, 02183718454, 123, 456]]
How can I get all numbers in an array in php?
This is not working so far:
if (isset($_GET["phone"])) {
$phone = $_GET['phone'];
$phpArray = json_decode($phone, true);
I hope you can help me again ;-)
If the JSON input to the PHP script really is this JSON
{ "phone": [ "123", "456", "789"] }
then PHP's json_decode should handle it without problems.
You can try this code to see it's actually working and use it to detect where something goes wrong:
// original JSON to send from the client
$jsonString = '{ "phone": [ "123", "456", "789"] }';
// build a query string with the JSON to send
$queryString = "?" . http_build_query(array("phone" => $jsonString));
echo "Query string to send is: " . $queryString . PHP_EOL;
// PHP side: this is not a real HTTP GET request, but to pretend we have
// got some data in, we'll use the same query string, parse it, and store it
// in $params
$incoming = parse_url($queryString, PHP_URL_QUERY);
parse_str($incoming, $params);
// now print contents of "phone" parameter
echo "URL parameter phone contains " . $params["phone"] . PHP_EOL;
// JSON-decode the "phone" parameter
var_dump(json_decode($params["phone"], true));
This should print:
Query string to send is: ?phone=%7B+%22phone%22%3A+%5B+%22123%22%2C+%22456%22%2C+%22789%22%5D+%7D
URL parameter phone contains { "phone": [ "123", "456", "789"] }
array(1) {
'phone' =>
array(3) {
[0] =>
string(3) "123"
[1] =>
string(3) "456"
[2] =>
string(3) "789"
}
}
which shows the JSON decodes to a proper PHP array. An array of strings, to be precise, and not numbers as requested. Turning the strings into numbers in PHP will be easy to do, but maybe you could also make sure on the call site that you send numbers and not strings.
If your original code does not work, I guess the incoming data is either no properly encoded JSON or there is some magic escaping going on (magic quotes hell, should be turned off in today's PHP, but could be a reason for garbled script input).
To make sure your JSON data is not truncated and to also save you from potential URL-encoding issues, I also suggest sending the JSON via HTTP POST, not HTTP GET.

Getting currency conversion data from Yahooapis now that iGoogle is gone

Up until yesterday I had a perfectly working budget organizer site/app working with iGoogle.
Through PHP, using the following little line
file_get_contents('http://www.google.com/ig/calculator?hl=en&q=1usd=?eur');
and similar I was able to get all I needed.
As of today, this is no longer working. When I looked into the issue, what has happened is that Google has retired iGoogle. Bummer!
Anyway, I was looking around elsewhere but I can't find anything that fits my needs. I would REALLY love to just fix it and get it running again by just switching this one line of code (i.e. changing the Google address with the address of some other currency API available) but it seems like none does.
The API from rate-exchange.appspot.com seems like it could be a iGoogle analog but, alas, it never works. I keep getting an "Over Quota" message.
(Here comes an initial question: anybody out there know of a simple, reliable, iGoogle-sort API?)
So I guess the natural thing would be to the Yahoo YQL feature (at least I suppose it is as reliable).
Yahoo's queries look like this:
http://query.yahooapis.com/v1/public/yql?q=select * from yahoo.finance.xchange where pair in ("USDEUR", "USDJPY", "USDBGN")&env=store://datatables.org/alltableswithkeys
What I really can't figure out is how to parse this data. It outputs an XML.
What I used to have is this:
function exchange($inputAmount,$inputCurrency,$outputCurrency) {
$exchange = file_get_contents('http://www.google.com/ig/calculator?hl=en&q='.$inputAmount.$inputCurrency.'=?'.$outputCurrency);
$exchange = explode('"', $exchange);
$exchange = explode('.', $exchange['3']);
$exchange[0] = str_replace(" ", "",preg_replace('/\D/', '', $exchange[0]));
if(isset($exchange[1])){
$exchange[1] = str_replace(" ", "",preg_replace('/\D/', '', $exchange[1]));
$exchange = $exchange[0].".".$exchange[1];
} else{
$exchange = $exchange[0];
}
return $exchange;
}
So the user was able to get the exchange rate from an input currency such as "USD" and an output currency such as "EUR" on a specific amount of money. As I said, this was working swimmingly up until yesterday night.
Any ideas?
Never mind! Solved it!
For anyone interested, here's what I did to get my code to work (with the least chnges possible) with the Yahoo YQL:
// ** GET EXCHANGE INFO FROM YAHOO YQL ** //
$url = 'http://query.yahooapis.com/v1/public/yql?q=select * from yahoo.finance.xchange where pair in ("USDEUR", "EURUSD")&env=store://datatables.org/alltableswithkeys'; //<-- Get the YQL info from Yahoo (here I'm only interested in converting from USD to EUR and vice-versa; you should add all conversion pairs you need).
$xml = simplexml_load_file($url) or die("Exchange feed not loading!"); //<-- Load the XML file into PHP variable.
$exchange = array(); //<-- Build an array to hold the data we need.
for($i=0; $i<2; $i++): //<-- For loop to get data specific to each exchange pair (you should change 2 to the actual amount of pairs you're querying for).
$name = (string)$xml->results->rate[$i]->Name; //<-- Get the name of the pair and turn it into a string (this looks like this: "USD to EUR").
$rate = (string)$xml->results->rate[$i]->Rate; //<-- Do the same for the actual rate resulting from the conversion.
$exchange[$name] = $rate; //<-- Put the data pairs into the array.
endfor; //<-- End for loop. :)
// ** WORK WITH EXCHANGE INFO ** //
$toeur = array( //<-- Create new array specific for conversion to one of the units needed.
'usd' => $exchange['USD to EUR'], //<-- Create an array key for each unit used. In this case, in order to get the conversion of USD to EUR I ask for it from my $exchange array with the pair Name.
'eur' => 1); //<-- The way I coded the app, I found it more practical to also create a conversion for the unit into itself and simply use a 1, which translates into "do not convert"
$tousd = array(
'eur' => $exchange['EUR to USD'],
'usd' => 1);
This is basically all you need to get all the exchange info you want. After that, you use it all something like this:
amount*$toxxx['coin'];
So, say I wanted to know how many Euro is 100 USD right now:
100*$toeur['usd'];
Piece of cake!
Still a very useful solution by QuestionerNo27. Since early 2015, however, Yahoo YQL apparently slightly changed the XML output of their api. 'Name' now no longer translates into a string like 'USD to EUR', but to 'USD/EUR' and should in the code above be referenced this way:
$toeur = array(
'usd' => $exchange['USD/EUR']
instead of
$toeur = array(
'usd' => $exchange['USD to EUR']
and in a similar fashion for other currency conversions.
I created a routine to convert the currency based on #QuestionerNo27 http://jamhubsoftware.com/geoip/currencyconvertor.php?fromcur=USD&tocur=EUR&amount=1 you can consume this
<?php
$fromcur = $_GET['fromcur'];
$tocur = $_GET['tocur'];
$amt = $_GET['amount'];
// ** GET EXCHANGE INFO FROM YAHOO YQL ** //
$url = 'http://query.yahooapis.com/v1/public/yql?q=select * from yahoo.finance.xchange where pair in ("'.$fromcur.$tocur.'")&env=store://datatables.org/alltableswithkeys'; //<-- Get the YQL info from Yahoo (here I'm only interested in converting from USD to EUR and vice-versa; you should add all conversion pairs you need).
$xml = simplexml_load_file($url) or die("Exchange feed not loading!"); //<-- Load the XML file into PHP variable.
$exchange = array(); //<-- Build an array to hold the data we need.
for($i=0; $i<2; $i++): //<-- For loop to get data specific to each exchange pair (you should change 2 to the actual amount of pairs you're querying for).
$name = (string)$xml->results->rate[$i]->Name; //<-- Get the name of the pair and turn it into a string (this looks like this: "USD to EUR").
$rate = (string)$xml->results->rate[$i]->Rate; //<-- Do the same for the actual rate resulting from the conversion.
$exchange[$name] = $rate; //<-- Put the data pairs into the array.
endfor; //<-- End for loop. :)
// ** WORK WITH EXCHANGE INFO ** //
$conv = $fromcur . '/' . $tocur;
$toeur = array( //<-- Create new array specific for conversion to one of the units needed.
$tocur => $amt*$exchange[$conv], //<-- Create an array key for each unit used. In this case, in order to get the conversion of USD to EUR I ask for it from my $exchange array with the pair Name.
$fromcur => $amt,
"ex_amt" =>$amt*$exchange[$conv]); //<-- The way I coded the app, I found it more practical to also create a conversion for the unit into itself and simply use a 1, which translates into "do not convert"
echo json_encode($toeur);
?>

Categories