I'm having a small problem while pulling tide data from the wunderground api. When I use the code below to pull the time of day for low tide I get an accurate answer one day, but a wrong answer the following day:
<?
$json_url = 'http://api.wunderground.com/api/b2b4a1ad0a889006/tide/q/NJ/Wildwood.json';
// jSON String for request
$json_string = '[http://api.wunderground.com/api/b2b4a1ad0a889006/tide/q/NJ/Wildwood.json]';
// Initializing curl
$ch = curl_init( $json_url );
// Configuring curl options
$options = array(
CURLOPT_RETURNTRANSFER => true,
);
// Setting curl options
curl_setopt_array( $ch, $options );
// Getting results
$result = curl_exec($ch); // Getting jSON result string
$parsed_json = json_decode($result);
$parsed_data->stats; //this returns
$low_tide_time = $parsed_json->tide->tideSummary[8]->date->pretty;
echo $low_tide_time;
?>
The reason for this is clear. The array key (in this case [8]) is not consistently assigned to the same tide data type (low tide) every day. So today [8] may be the array key associated with the time for low tide, but tomorrow [8] will be the array key assigned to sunrise, moonrise, etc.
Is there a way to use a for each loop to grab the time for low tide?
Thanks!
I check JSON format and it should works:
foreach( $parsed_json->tide->tideSummary AS $tideSummary ) {
if( $tideSummary->data->type == "Low Tide" ) {
$low_tide_time = $tideSummary->date->pretty;
echo $low_tide_time;
// you can end of foreach
break;
}
}
If there is something unique in the $parsed_json->tide->tideSummary Object which belongs to your requested information (like "Title: Low Tide") you could do a foreach loop and check if that value is present.
Like this
foreach ($parsed_json->tide->tideSummary AS $tideSummary) {
if ($tideSummary->title == "Low Tide") {
$LowTide = $tideSummary;
}
}
You can access the Low Tide data after that like this:
echo $LowTide->Date;
PS: Untested and no info about your JSON Format, if there is no unique information to identify Low Tide it could get tricky..
Related
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.)
I'm making an api call that return only 100 records:
$response = $api->order->{"events"}->get();
To get next 100 records I have to call api with last ID from response, for example:
$response = $api->order->{"events?from=LAST_ID"}->get();
So how to make iteration to get all records?
I had a similar task in different projects, and I use a while() iteration. It might not be the cleanest solution, but it gets the job done.
$response = $api->order->{"events"}->get();
while ( $response->count > 0 ) :
// Do something with $response
$response = $api->order->{"events?from=LAST_ID"}->get();
endwhile;
Output when success
string(66)
"{"status":true,"message":"success","data":{"amountDue":"-504.20"}}"
Output when error
string(119) "{"status":false,"message":"An error occured while getting
full subscriber profile: Subscription not found MPP servers"}"
How should I write in php to get the amount due from the output? I am new to REST api. Can someone show me ? Thank you
That is a JSON-encoded response. Use json_decode() to convert the string back into an array, and then access the array element:
$output = '{"status":true,"message":"success","data":{"amountDue":"-504.20"}}';
$results = json_decode($output,true);
if($results["status"])
{
echo "Success! Data: " . print_r($results,true);
}
I assume that you can at least send proper request to the endpoint and you are able to capture the response.
You receive a json string which must be parses so if:
$response = '{"status":true,"message":"success","data":{"amountDue":"-504.20"}}';
$responseArray = json_decode($response, true);
Then you will get a responseArray as associated array (the second parameter) so you can get amount due like that
$amountDue = $responseArray['data']['amountDue'];
You could also parse json data into an StdClass which turn all fields in json into an object's property. To do that abandon the second parameter in json_decode function
$resultObj = json_decode($response);
$amountDue = $resultObj->data['amountDue'];
All depends on your requests.
To read more about json_decode try documentation
I am working with the Ecwid API, and now moving towards updating my order from our fulfillment site with tracking info and shipping status.
Fulfillment Operation is going to export a xml file of the order update.
I have first created the basic script to update a product and this works fine.
// Post Tracking number and change Status to shipped
// trackingNumber : ""
// fulfillmentStatus : "SHIPPED"
$storeID = "";
$myToken = "";
$data = array("trackingNumber" => "9405503699300250719362", "fulfillmentStatus" => "SHIPPED", "orderNumber" => "7074");
$data_string = json_encode($data);
$url = "https://app.ecwid.com/api/v3/".urlencode($storeID)."/orders/".$data['orderNumber']."?token=".$myToken;
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json','Content-Length: ' . strlen($data_string)));
$response = curl_exec($ch);
curl_close($ch);
I've also created the script to pull in the xml file and convert to json to 'put' the data over to the shopping cart.
<?php
// The file data.xml contains an XML document with a root element
// and at least an element /[root]/title.
if (file_exists('data.xml')) {
$xml = simplexml_load_file('data.xml');
print_r($xml);
} else {
exit('Failed to open data.xml.');
}
$data_string = json_encode($xml);
echo '<br> br>';
echo "<pre>";
print_r($data_string);
?>
Now this is where i am lost to put the two parts together so that it would loop through the xml file (json content) with multiple "orderNumber(s)" and update the trackingNumber and fulfillmentStatus of each order.
Vitaly from Ecwid team here.
I see that you want to update orders in your Ecwid store via API from an XML file.
So the whole process is:
get details of XML file
parse data in it, find out the total number of orders there
form a loop for each order in the file
make a request to Ecwid API to update order in each loop
In your second code snippet, I see print_r($data_string); - what does it print to the screen?
I imagine the next steps would be:
Manage to correctly find order details in the XML file (order
number, tracking number) while in the loop
Make each loop update specific order in the store
For the step 1, I suggest saving data from XML file to a convenient format for you in PHP, e.g. object or array.
For example, if it was an array, it will be something like this:
Array = [recordArray 1, recordArray 2, recordArray 3]
recordArray = [ orderNumber, trackingNumber ]
For the step 2: So each loop will go through an recordArray in the Array and then get the necessary orderNumber and trackingNumber for the request.
Then the request will use this data to update an order in your Ecwid store, just like you shown in the code snippet above. However the values: 9405503699300250719362 and 7074 will be dynamic and different for each loop.
If you have any questions, please feel free to contact me: http://developers.ecwid.com/contact
Thank you.
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);
?>