Performing a Simple Search Request Using SerpApi in PHP Without GuzzleHTTP

Answered using ChatGPT 4o by ChatGPT4o

Question:

A simple search request via serpapi.com api, for PHP; without GuzzleHTTP

Answer:

Certainly! If you want to perform a simple search request using the SerpApi in PHP without using GuzzleHTTP, you can use PHP's built-in file_get_contents function along with http_build_query to construct the query string. Below is an example of how you can achieve this:

  1. Sign up for SerpApi: First, make sure you have an API key from SerpApi. You can sign up at serpapi.com to get your API key.

  2. PHP Code: Use the following PHP code to perform a search request:

<?php
// Your SerpApi API key
$api_key = 'YOUR_API_KEY';

// Search query parameters
$params = [
    'engine' => 'google', // Search engine
    'q' => 'coffee',      // Search query
    'api_key' => $api_key // Your API key
];

// Construct the query URL
$base_url = 'https://serpapi.com/search';
$query_url = $base_url . '?' . http_build_query($params);

// Perform the GET request
$response = file_get_contents($query_url);

// Check if the request was successful
if ($response === FALSE) {
    die('Error occurred');
}

// Decode the JSON response
$data = json_decode($response, true);

// Print the response data
print_r($data);
?>

Explanation:

  1. API Key: Replace 'YOUR_API_KEY' with your actual SerpApi API key.
  2. Search Parameters: The $params array contains the search parameters. In this example, we are using the Google search engine ('engine' => 'google') and searching for the term 'coffee' ('q' => 'coffee').
  3. Query URL: The http_build_query function is used to construct the query string from the $params array. This is appended to the base URL (https://serpapi.com/search) to form the complete query URL.
  4. GET Request: The file_get_contents function is used to perform the GET request to the constructed query URL.
  5. Error Handling: If the request fails, the script will terminate with an error message.
  6. JSON Decoding: The JSON response is decoded into a PHP associative array using json_decode.
  7. Output: The response data is printed using print_r.

This code will perform a search request to SerpApi and print the results. Make sure to handle the response data according to your needs.