A simple search request via serpapi.com api, for PHP.
Sure! To perform a simple search request using the SerpApi in PHP, you need to follow these steps:
Sign up for SerpApi: First, you need to sign up for an account at SerpApi. After signing up, you will get an API key.
Install GuzzleHTTP: SerpApi recommends using GuzzleHTTP for making HTTP requests in PHP. You can install it via Composer. If you don't have Composer installed, you can download it from getcomposer.org.
composer require guzzlehttp/guzzle
Write the PHP code: Below is a simple example of how to perform a search request using SerpApi with GuzzleHTTP.
<?php
require 'vendor/autoload.php';
use GuzzleHttp\Client;
// Your SerpApi API key
$apiKey = 'YOUR_API_KEY';
// Create a new GuzzleHTTP client
$client = new Client();
// Define the search parameters
$params = [
'engine' => 'google', // Search engine to use
'q' => 'Coffee', // Search query
'api_key' => $apiKey // Your SerpApi API key
];
// Make the request to SerpApi
$response = $client->request('GET', 'https://serpapi.com/search', [
'query' => $params
]);
// Get the response body
$body = $response->getBody();
$data = json_decode($body, true);
// Print the search results
print_r($data);
Run the PHP script: Save the script to a file, for example, search.php
, and run it from the command line:
php search.php
This script will perform a search for "Coffee" using the Google search engine via SerpApi and print the results.
'YOUR_API_KEY'
with your actual SerpApi API key.This example uses GuzzleHTTP for simplicity and reliability, but you can use any HTTP client library you prefer.