Performing DuckDuckGo Search in PHP Without GuzzleHTTP Using file_get_contents or cURL

Answered using ChatGPT 4o by ChatGPT4o

Question:

A simple search request via DuckDuckGo (official API or unofficial method), for PHP; without GuzzleHTTP

Answer:

Sure, you can perform a simple search request using DuckDuckGo in PHP without using GuzzleHTTP. Instead, you can use PHP's built-in file_get_contents function or cURL. Below is an example using both methods:

Using file_get_contents

<?php
$query = "example search";
$encodedQuery = urlencode($query);
$url = "https://duckduckgo.com/?q={$encodedQuery}&format=json";

$options = [
    "http" => [
        "header" => "User-Agent: PHP"
    ]
];

$context = stream_context_create($options);
$response = file_get_contents($url, false, $context);

if ($response === FALSE) {
    die('Error occurred');
}

$data = json_decode($response, true);
print_r($data);
?>

Using cURL

<?php
$query = "example search";
$encodedQuery = urlencode($query);
$url = "https://duckduckgo.com/?q={$encodedQuery}&format=json";

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_USERAGENT, 'PHP');

$response = curl_exec($ch);

if (curl_errno($ch)) {
    echo 'Error:' . curl_error($ch);
    curl_close($ch);
    die();
}

curl_close($ch);

$data = json_decode($response, true);
print_r($data);
?>

Explanation

  1. URL Encoding: The search query is URL-encoded to ensure it is properly formatted for the URL.
  2. User-Agent: Some servers require a User-Agent header to be set. This is done in both examples.
  3. Error Handling: Basic error handling is included to check if the request was successful.

Note

DuckDuckGo's official API is called DuckDuckGo Instant Answer API, and it has some limitations. The above examples use the format=json parameter to request JSON data, but DuckDuckGo may not support this parameter directly in search queries. You might need to use their Instant Answer API for more structured data.

For more advanced usage or if you encounter issues, consider checking DuckDuckGo's official documentation or using a more robust HTTP client library if possible.