How to add dimensions to Google analytics api requets - php

The examples given by Google are a very simple query request. however, when I try to add more parameters, it will throw errors and I don't exactly know how to structure the syntax.
This simple query request works:
return $analytics->data_ga->get(
'ga:' . $viewID,
$startDate,
$endDate,
'ga:sessions'
);
I need more information and I've already used Google's Query Explorer to get the Information but I just don't know how to structure my PHP query. The Information I want to request is also ga:pageviews as another metric, ga:pagePath and ga:pageTitle as dimensions and also a filter. I already fail at adding a second metric.
I have tried this:
return $analytics->data_ga->get(
'ga:' . $viewID,
$startDate,
$endDate,
'ga:sessions',
'ga:pageviews'
);
simply adding it doesn't work. Can anyone point me in the correct direction?

Dimensions need to be added as option parms
//Adding Dimensions
$params = array('dimensions' => 'ga:userType');
// requesting the data
$data = $service->data_ga->get("ga:89798036", "2014-12-14", "2014-12-14", "ga:users,ga:sessions", $params );

Related

Twitter API - Count number of tweets of a specific string

I'm using the twitter api to try to get an integer that tells me how many tweets there are to a certain string I give.
e.g. I search for "mercedes" and then want to get an integer back from twitter that says: "1249". 1249 would mean that there were so many tweets in the last 2 weeks. Twitter only returns data from the last 2 weeks as far as I know. Because of me it's also okay if I get all records back and pull them by means of php or the like. I have already sent some test requests, but always only get arrays back with a maximum of 20 entries.
Anyone have a solution?
And I already looked at similar questions but couldn't find something that helped me. Many answers in the questions I have seen no longer work, as twitter and its api has changed and evolved
Using the public search API, you will get tweets from the last 7 days only and not all tweets. So your results won't be accurate.
If you still want to test, you have to use the standard search API :
https://developer.twitter.com/en/docs/tweets/search/api-reference/get-search-tweets.html
Set the "cout" parameter to 100, and check the "next_results" value in the results to loop 100 others tweets and so on until you get no result.
I couldn't find a solution neither, so I coded it using pieces of code and ideas as the previous #JeffProd one, and avoiding using a lib. I hope it could help you.
PS: You must apply for a Twitter Developer Account and create an app to get your TOKENs and KEYs.
<?php
//Access token & access token secret
define("TOKEN", 'XXXXXXXXXXXXXXXX'); //Access token
define("TOKEN_SECRET", 'XXXXXXXXXXXXXXXX'); //Access token secret
//Consumer API keys
define("CONSUMER_KEY", 'XXXXXXXXXXXXXXXX'); //API key
define("CONSUMER_SECRET", 'XXXXXXXXXXXXXXXX'); //API secret key
$method='GET';
$host='api.twitter.com';
$path='/1.1/search/tweets.json'; //API call path
$url="https://$host$path";
//Query parameters
$query = array(
'q' => 'wordtosearch', /* Word to search */
'count' => '100', /* Specifies a maximum number of tweets you want to get back, up to 100. As you have 100 API calls per hour only, you want to max it */
'result_type' => 'recent', /* Return only the most recent results in the response */
'include_entities' => 'false' /* Saving unnecessary data */
);
//time window in hours
define("WINDOW", 1);
//Authentication
$oauth = array(
'oauth_consumer_key' => CONSUMER_KEY,
'oauth_token' => TOKEN,
'oauth_nonce' => (string)mt_rand(), //A stronger nonce is recommended
'oauth_timestamp' => time(),
'oauth_signature_method' => 'HMAC-SHA1',
'oauth_version' => '1.0'
);
//Used in Twitter's demo
function add_quotes($str) { return '"'.$str.'"'; }
//Searchs Twitter for a word and get a couple of results
function twitter_search($query, $oauth, $url){
global $method;
$arr=array_merge($oauth, $query); //Combine the values THEN sort
asort($arr); //Secondary sort (value)
ksort($arr); //Primary sort (key)
$querystring=http_build_query($arr,'','&');
//Mash everything together for the text to hash
$base_string=$method."&".rawurlencode($url)."&".rawurlencode($querystring);
//Same with the key
$key=rawurlencode(CONSUMER_SECRET)."&".rawurlencode(TOKEN_SECRET);
//Generate the hash
$signature=rawurlencode(base64_encode(hash_hmac('sha1', $base_string, $key, true)));
//This time we're using a normal GET query, and we're only encoding the query params (without the oauth params)
$url=str_replace("&","&",$url."?".http_build_query($query));
$oauth['oauth_signature'] = $signature; //Don't want to abandon all that work!
ksort($oauth); //Probably not necessary, but twitter's demo does it
$oauth=array_map("add_quotes", $oauth); //Also not necessary, but twitter's demo does this too
//This is the full value of the Authorization line
$auth="OAuth ".urldecode(http_build_query($oauth, '', ', '));
//If you're doing post, you need to skip the GET building above and instead supply query parameters to CURLOPT_POSTFIELDS
$options=array( CURLOPT_HTTPHEADER => array("Authorization: $auth"),
//CURLOPT_POSTFIELDS => $postfields,
CURLOPT_HEADER => false,
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_SSL_VERIFYPEER => false);
//Query Twitter API
$feed=curl_init();
curl_setopt_array($feed, $options);
$json=curl_exec($feed);
curl_close($feed);
//Return decoded response
return json_decode($json);
};
//Initializing
$done = false; //Loop flag
$countTweets=0; //Tweets fetched
$twitter_data = new stdClass();
$now=new DateTime(date('D M j H:i:s O Y')); //Current search time
//Fetching starts
do{
$twitter_data = twitter_search($query,$oauth,$url);
//Partial results, updating the total amount of tweets fetched
$countTweets += count($twitter_data->statuses);
//If not all the tweets have been fetched, then redo...
if(isset($twitter_data->search_metadata->next_results)){
//Parsing information for max_id in tweets fetched
$string="?max_id=";
$parse=explode("&",$twitter_data->search_metadata->next_results);
$maxID=substr($parse[0],strpos($parse[0],$string)+strlen($string));
$query['max_id'] = -1+$maxID; //Returns results with an ID less than (that is, older than) or equal to the specified ID, to avoid getting the same last tweet
//Twitter will be queried again, this time with the addition of 'max_id'
}else{
$done = true;
}
}while(!$done);
//If all the tweets have been fetched, then we are done
echo "<p>query: ".urldecode($query['q'])."</p>";
echo "<p>tweets fetched: ".$countTweets."</p>";
?>

Google Analytics, Dimensions & Metrics - How to?

I've finally figured out how i connected to the Google Analytics, correct - and I'm now able to access data to some point. I'm using the google-api-php-client.
I can work with metrics just fine fx, by doing
return $analytics->data_ga->get(
'ga:' . $profileId,
'7daysAgo',
'today',
'ga:sessions,ga:pageviews,ga:sessionDuration');
which will return me number of sessions, pageviews, and session duration. But now lets say I am interested in using some of the dimensions as well - Maybe i want the query return site usage data for all traffic by search engine, sorted by pageviews in descending order.
dimensions=ga:source
metrics=ga:pageviews,ga:sessionDuration,ga:exits
filters=ga:medium==cpa,ga:medium==cpc,ga:medium==cpm,ga:medium==cpp,ga:medium==cpv,ga:medium==organic,ga:medium==ppc
sort=-ga:pageviews
the data_ga->get function calls for the following parameters: $ids, $startDate, $endDate, $metrics, $optParams = array()
I tried supplying the dimensions and filters in a array, but it returns me the following errors
Warning: Illegal string offset 'type' in
xxxxxxxxx/src/Google/Service/Resource.php on line 269
Warning: Illegal string offset 'location' in
xxxxxxxxx/src/Google/Service/Resource.php on line 272
Warning: Illegal string offset 'location' in
xxxxxxxxx/src/Google/Service/Resource.php on line 274
Dimensions are not required so there for they are part of option parameters.
//Adding Dimensions
$params = array('dimensions' => 'ga:userType');
// requesting the data
$data = $service->data_ga->get("ga:89798036", "2014-12-14", "2014-12- 14", "ga:users,ga:sessions", $params );
Filters and sort can also be added to the $parms array

How to use parameters in Google Analytics API

How to use parameters in getResults function? I need to get information about what urls of my website users are watching. In case when i use ga:sessions, I see how many users was there. If I change it to ga:pageviews the number (in result array) is changes. So it means that API is "alive".
How do I get URLs "points of enter" where people starting to watch my website. And how to send parameters in this place 'ga:sessions'); ?
API instructions I was reading are here.
function getResults(&$analytics, $profileId) {
// Calls the Core Reporting API and queries for the number of sessions
// for the last seven days.
return $analytics->data_ga->get(
'ga:' . $profileId,
'7daysAgo',
'today',
'ga:sessions');
}
function printResults(&$results) {
// Parses the response from the Core Reporting API and prints
// the profile name and total sessions.
if (count($results->getRows()) > 0) {
// Get the profile name.
$profileName = $results->getProfileInfo()->getProfileName();
// Get the entry for the first entry in the first row.
$rows = $results->getRows();
// $sessions = $rows[0][0];
// Print the results.
echo '<pre>';
print_r($rows);
} else {
print "No results found.\n";
}
}
For now result is:
Array
(
[0] => Array
(
[0] => 3585
)
)
When you run your request
$analytics->data_ga->get('ga:' . $profileId,
'7daysAgo',
'today',
'ga:sessions');
What you are doing is asking Google Analytics to give you the number of sessions for your profile between today and 7 days ago. Which it is infact doing. There have been 3585 sessions during that time frame
Now if you check the dimensions and metrics explorer you will find a large list of dimensions and metrics. ga:sessions is a metric ga:pageviews is a dimension so you need to add the dimension to your request.
$params = array('dimensions' => 'ga:pageviews');
$analytics->data_ga->get('ga:' . $profileId,
'7daysAgo',
'today',
'ga:sessions',
$params);
Now run your request and you should get a list of each page with the total number of sessions for that page.
Tip:
foreach ($results->getRows() as $row) {
print $row[0]." - ".$row[1];
}

Get function in Google Analytics API

I'm trying to fetch some data using the analytics API, the example i have is this:
function getResults(&$analytics, $profileId) {
// Calls the Core Reporting API and queries for the number of sessions
// for the last seven days.
return $analytics->data_ga->get(
'ga:' . $profileId,
'7daysAgo',
'today',
'ga:sessions');
}
and the function in the Analytics.php file is:
public function get($ids, $metrics, $optParams = array())
{
$params = array('ids' => $ids, 'metrics' => $metrics);
$params = array_merge($params, $optParams);
return $this->call('get', array($params), "Google_Service_Analytics_RealtimeData");
}
}
How do I adapt that example to return some dimensions along with the sessions, for example, pagePath?
Thanks
So the question is little unclear, but the first part of your question is correct, that example works and is the way to get data from the Google Analytics API. You do NOT need to touch or modify Analytics.php however.
Here is what your code should look like:
$ga_profile_id = xxxxxxx; // insert yours
$from = date('Y-m-d', time()-2*24*60*60); // last 2 days
$to = date('Y-m-d'); // today
$metrics = 'ga:visits,ga:visitors,ga:pageviews';
$dimensions = 'ga:date';
$sort = "-ga:visits";
$data = $service->data_ga->get('ga:'.$ga_profile_id, $from, $to, $metrics, array('dimensions' => $dimensions,'sort'=>$sort));
These are all the basic elements you need to get started. Visit https://developers.google.com/analytics/devguides/reporting/core/v3/common-queries for a list of Common Query recipes. Replace the metrics, dimensions and sort parameters in my example above with the ones listed there to run the common report scenarios they cover.
The Analytics API Query explorer (https://ga-dev-tools.appspot.com/query-explorer/) is a great to play around and discover the metric and dimension names. For example, you'll find that that the dimension for Page Path is: ga:pagePath.
So then, for example, if you want to get visits and pageviews by page path, you simply insert the correct parameters in the code, and you get something that looks like this:
$ga_profile_id = xxxxxx; //insert yours here
$from = date('Y-m-d', time()-2*24*60*60); // last 2 days
$to = date('Y-m-d'); // today
$metrics = 'ga:visits,ga:pageviews';
$dimensions = 'ga:pagePath';
$sort = "-ga:visits";
$data = $service->data_ga->get('ga:'.$ga_profile_id, $from, $to, $metrics, array('dimensions' => $dimensions,'sort'=>$sort));
Which basically means:
Get the metrics visits and pageviews, using page path as the dimension, and sort it by visits - for the last 2 days! Hopefully this all makes sense.
I'm a bit unfamiliar with php syntax but you can specify dimension types in your params when query-ing for example for pagepath you could try
$params = array('ids' => $ids, 'metrics' => $metrics, 'dimensions' => 'rt:pagePath')
See the official dimensions and metrics explorer for more info

Sort the tweets by date using Twitter Search API

I have written an application that searches tweets for a specific keyword using the twitter API, but i am trying to find a way to display the latest tweets first, i am unable to find a way to sort the tweets received as a response.
I am referring to link https://dev.twitter.com/docs/api/1.1/get/search/tweets and below is my code
I have included all necessary files and set all required parameters
function search(array $query)
{
$toa = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, ACCESS_TOKEN, ACCESS_TOKEN_SECRET);
return $toa->get('search/tweets', $query);
}
$query = array(
"q" => "Sachin Tendulkar",
"count" => 10,
"result_type" => "popular"
);
$results = search($query);
Any help on this would be appreciated. Thanks
To display the latest tweet, you should use result_type as recent.
$query = array(
"q" => "Sachin Tendulkar",
"count" => 10,
"result_type" => "recent"
);
More about result_type paramater :
mixed: Include both popular and real time results in the response.
recent: return only the most recent results in the response.
popular: return only the most popular results in the response.

Categories