|
| 1 | +<?php |
| 2 | + |
| 3 | +# This script makes a GET request to the /searches endpoint on the Analytics REST API - https://www.algolia.com/doc/rest-api/analytics/. |
| 4 | +# To get the top 1000 searches over the last 7 days. |
| 5 | +# There is no API client for Analytics, so this script uses the PHP Requests library to make the call. |
| 6 | + |
| 7 | +require __DIR__ . '/vendor/autoload.php'; |
| 8 | + |
| 9 | +$dotenv = Dotenv\Dotenv::createImmutable(__DIR__); |
| 10 | +$dotenv->load(); |
| 11 | + |
| 12 | +# Get your Algolia Application ID and (admin) API key from the dashboard: https://www.algolia.com/account/api-keys |
| 13 | +# and choose a name for your index. Add these environment variables to a `.env` file: |
| 14 | +$ALGOLIA_APP_ID = $_ENV['ALGOLIA_APP_ID']; |
| 15 | +$ALGOLIA_API_KEY = $_ENV['ALGOLIA_API_KEY']; |
| 16 | +$ALGOLIA_INDEX_NAME = $_ENV['ALGOLIA_INDEX_NAME']; |
| 17 | + |
| 18 | +# The Analytics API can be reached from multiple domains, each specific to a region. |
| 19 | +# You should use the domain that matches the region where your analytics data is stored and processed. |
| 20 | +# View your analytics region: https://www.algolia.com/infra/analytics |
| 21 | +# The following domains are available: |
| 22 | +# United States: https://analytics.us.algolia.com |
| 23 | +# Europe (Germany): https://analytics.de.algolia.com |
| 24 | + |
| 25 | +$URL_DOMAIN = $_ENV['URL_DOMAIN']; |
| 26 | + |
| 27 | +$url = "$URL_DOMAIN/2/searches?index=$ALGOLIA_INDEX_NAME&limit=1000"; |
| 28 | + |
| 29 | +# Describing HTTP request |
| 30 | +$request_options = [ |
| 31 | + 'http' => [ |
| 32 | + 'method' => 'GET', |
| 33 | + 'header' => join("\r\n", [ |
| 34 | + "X-Algolia-Application-Id: $ALGOLIA_APP_ID", |
| 35 | + "X-Algolia-API-Key: $ALGOLIA_API_KEY", |
| 36 | + ]), |
| 37 | + ] |
| 38 | +]; |
| 39 | + |
| 40 | +# Sending HTTP request |
| 41 | +$result = file_get_contents($url, false, stream_context_create($request_options)); |
| 42 | + |
| 43 | +if ($result === FALSE) { |
| 44 | + exit("Failed HTTP request"); |
| 45 | +} |
| 46 | + |
| 47 | +# Returning 1000 Top Searches |
| 48 | +print("1000 Top Searches:\n"); |
| 49 | +var_dump($result); |
| 50 | + |
| 51 | +# Format the resulting json string |
| 52 | +$json = json_decode($result); |
| 53 | +$formatted_result = json_encode($json, JSON_PRETTY_PRINT); |
| 54 | + |
| 55 | +# Write json to file |
| 56 | +if (file_put_contents("{$ALGOLIA_INDEX_NAME}_top_1000_searches.json", $formatted_result)) |
| 57 | + echo "JSON file created successfully...\n"; |
| 58 | +else |
| 59 | + echo "Oops! Error creating json file...\n"; |
0 commit comments