A simple search request via serpapi.com api, for PHP; without GuzzleHTTP
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:
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.
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);
?>
'YOUR_API_KEY'
with your actual SerpApi API key.$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'
).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.file_get_contents
function is used to perform the GET request to the constructed query URL.json_decode
.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.