A simple search request via DuckDuckGo (official API or unofficial method), for PHP; without GuzzleHTTP
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:
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);
?>
<?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);
?>
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.