How To Query Google Sheet via Guzzle Client PHP - php

I am using the google drive php library to access a google sheet on the api drive.
The first row of the sheet contains the column headings.
$httpClient = new GuzzleHttp\Client(['headers' => $headers]);
// This code works just fine and retrieves all rows of the sheet:
$resp = $httpClient->request('GET', $url);
However, I want to retrieve a subset of the rows based on the value in one column. I have tried each of these methods and all of them return all the rows instead of the subset.
$resp = $httpClient->request('GET', $url, ['query' => 'county=Sonoma']);
$resp = $httpClient->request('GET', $url, ['query' => ['county' => 'Sonoma']]);
$resp = $httpClient->request('GET', $url.'?county=Sonoma');
I am beginning to think I need to reference the column 'county' in a different way. Does anyone have any ideas of how I can make this work?
Thanks in advance.

I found this to work:
$resp = $httpClient->request('GET', $url.'?sq=county=Sonoma');

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

need help in PHP soap

i try to fetch result from www.tadawul.com.sa with php soap client.
but when i try to load that , get nothing just loading page.
here is my code.
$reference = array(
'companyId' => '*********',
'secureKey' => '*********'
);
$client = new SoapClient('http://www.tadawul.com.sa/Tadawul_WebAPI/services/GetDetailQuote?wsdl');
$response = $client->getDetailQuoteForCompany($reference);
var_dump($response);
I think the problem is in the structure you need to pass a getDetailQuoteForCompanyRequest Object not an array
Why don't you use wsdl2phpgenerator
It'll make you life easier, You need to pass wsdl file and it will generate all the classes that you need
Instead of this
$response = $client->getDetailQuoteForCompany($reference);
Try
$response = $client->__soapCall("getDetailQuoteForCompany", array($reference));

i am using a rest API i need to parse a forever changing json result

Okay so here goes i am using a rest api called strichliste
i am creating a user credit payment system
i am trying to grab a users balance by username problems is
my restapi i can only get the blanace via its userid
I have created a bit of php that grabs all the current users and the corresponding id and balance using this below
function getbal(){
// Get cURL resource
$curl = curl_init();
// Set some options - we are passing in a useragent too here
curl_setopt_array($curl, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => 'https://example.io:8081/user/'
)
);
// Send the request & save response to $resp
$resp = curl_exec($curl);
// Close request to clear up some resources
curl_close($curl);
print_r($resp);
}
this is the resulting respinse i get after using this in my main php script
<? getbal(); ?>
result --- #
{
"overallCount":3,
"limit":null,
"offset":null,"entries":[
{"id":1,
"name":"admin",
"balance":0,
"lastTransaction":null
},
{"id":2,
"name":"pghost",
"balance":0,
"lastTransaction":null
},
{"id":3,
"name":"sanctum",
"balance":0,
"lastTransaction":null
}
]
}
as you can see there are only currently 3 users but this will grow everyday so the script needs to adapt to growing numbers of users
inside my php script i have a var with the currently logged in use so example
$user = "sanctum";
i want a php script that will use the output fro gatbal(); and only output the line for the given user in this case sanctum
i want it to output the line in jsondecode for the specific user
{"id":3,"name":"sanctum","balance":0,"lastTransaction":null}
can anyone help
$user = "sanctum";
$userlist = getbal();
function findUser($u, $l){
if(!empty($l['entries'])){
foreach($l['entries'] as $key=>$val){
if($val['name']==$user){
return $val;
}
}
}
}
This way, once you have the list, and the user, you can just invoke findUser() by plugging in the userlist, and the user.
$userData = findUser($user, $userlist);
However, I would suggest finding a way to get the server to return only the user you are looking for, instead of the whole list, and then finding based on username. But thats another discussion for another time.

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.

How can I write a PHP script that will grab the follower count in Twitter for a given user?

All I want to do is get the Twitter follower count for a given user, say John Mayer. I want to store this value in a variable $testCount and that's it. I'm not writing an application or anything with any other users (all the documentation seems to revolve around the assumption that other users will be doing this)
The reason I'm storing the value is because in my PHP script, all I want to do is store this value in a mySQL table. Storing the value isn't the problem, it's retrieving it from Twitter's API. The eventual goal is to run this script every day and have it get an updated count of John Mayer's followers.
I've looked at other stack overflow answers and tried J7mbo's 'TwitterAPIExchange' method. So far I have this:
require_once('TwitterAPIExchange.php'); // TwitterAPIExchange.php is in the same folder as the //script I am modifying
$settings = array(
'oauth_access_token' => " my token",
'oauth_access_token_secret' => "my secret",
'consumer_key' => "my consumer key",
'consumer_secret' => "my consumer secret"
);
$url = 'https://api.twitter.com/1.1/users/show.json?screen_name=JohnMayer';
$requestMethod = 'GET';
$getfield = '?screen_name=JohnMayer';
$twitter = new TwitterAPIExchange($settings);
$follow_count=$twitter->setGetfield($getfield)
->buildOauth($url, $requestMethod)
->performRequest();
$testCount = json_decode($follow_count, true);
echo $testCount[0]['user']['followers_count'];
the Echo simply doesn't print anything. I've been working at this for days and can't seem to figure out how to grab this one statistic using php. Please someone help me adjust or alter my current script to achieve this seemingly simple goal.
For anyone this might help, I figured it out. Here is my function that gets twitter followers, it is a modification on one from Codeforest but I took out a bunch of stuff involving something called cache.php and a bunch of other stuff that caused it to have errors.
function getTwitterFollowers($screenName = 'codeforest')
{
require_once('TwitterAPIExchange.php');
// this variables can be obtained in http://dev.twitter.com/apps
// to create the app, follow former tutorial on http://www.codeforest.net/get-twitter-follower-count
$settings = array(
'oauth_access_token' => "youraccesstoken",
'oauth_access_token_secret' => "youraccesstokensecret",
'consumer_key' => "yourconsumerkey",
'consumer_secret' => "yourconsumersecret"
);
// forming data for request
$apiUrl = "https://api.twitter.com/1.1/users/show.json";
$requestMethod = 'GET';
$getField = '?screen_name=' . $screenName;
$twitter = new TwitterAPIExchange($settings);
$response = $twitter->setGetfield($getField)
->buildOauth($apiUrl, $requestMethod)
->performRequest();
$followers = json_decode($response);
$numberOfFollowers = $followers->followers_count;
return $numberOfFollowers;
}
Now this code works, I can store the follower count in variable like so:
$twitterfollow = getTwitterFollowers('dadalife');
Good luck to anyone else struggling with Twitter's new absurd API

Categories