Skip to content

Instantly share code, notes, and snippets.

@diguinhorocks
Last active September 20, 2019 16:07
Show Gist options
  • Save diguinhorocks/4237748 to your computer and use it in GitHub Desktop.
Save diguinhorocks/4237748 to your computer and use it in GitHub Desktop.
Simple Google Custom Search API requester
<!DOCTYPE HTML>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<form action="search.php" method="GET">
<label for="">Pesquisar: </label> <input type="text" name="q" />
</form>
</body>
</html>
<?php
class Request
{
protected $url;
protected $request;
protected $response;
protected $curl;
public function __construct(){ }
public function setQuery($query)
{
$this->query = $query;
return $this;
}
public function go()
{
$this->curl = curl_init();
curl_setopt( $this->curl , CURLOPT_URL , ltrim( $this->queryURL() . '&q=' . urlencode($this->query) ) );
curl_setopt( $this->curl , CURLOPT_SSL_VERIFYPEER , false );
curl_setopt( $this->curl , CURLOPT_RETURNTRANSFER , 1 );
$this->response = curl_exec($this->curl);
curl_close($this->curl);
return $this->getResponse();
}
public function getResponse()
{
header('Content-Type: application/atom+xml');
echo $this->response;
}
protected function queryURL()
{
return <<<URL
https://www.googleapis.com/customsearch/v1?key={google_api_key}&cx={your_cx}&alt=atom
URL;
}
}
<?php
include 'Request.php';
$c = new Request();
echo $c->setQuery($_GET['q'])->go();
@diguinhorocks
Copy link
Author

diguinhorocks commented Sep 20, 2019

@blks you should consider modifying the getResponse() and i suggest the use of SimpleXML to get the result as you wish.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment