Skip to content

Instantly share code, notes, and snippets.

@twhitney11
Created September 29, 2012 05:12
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save twhitney11/3803240 to your computer and use it in GitHub Desktop.
Save twhitney11/3803240 to your computer and use it in GitHub Desktop.
Simple Solr Interfacing PHP Class
<?php
//Solr interfacing class
class Solr
{
//For the constructor
public $solr_url;
public function __construct($url)
{
$this->solr_url = $url;
}
//Queries Solr for the given request
public function getQuery($query = '*')
{
$docNames = array();
$xml = new DOMDocument();
$xml->load( $this->solr_url . "/select/?q=" . urlencode($query) );
$docs = $xml->getElementsByTagName('doc');
foreach($docs as $doc){
$items = $doc->getElementsByTagName('str');
foreach($items as $item){
if($item->getAttribute('name') == 'id'){
$docNames[] = $item->nodeValue;
break;
}
}
}
return $docNames;
}
//Adds an item to the Solr index and also "commits" it for indexing
public function addAndCommitSolrDocument($name,$doc_path)
{
$post_data = array();
//Solr URL on which we have to post data
$url = $this->solr_url . "/update/extract?literal.id=" . urlencode($name) . "&commit=true";
//Any other field you might want to catch
$post_data['name'] = $name;
//File you want to upload/post
$post_data['file'] = "@" . $doc_path;
//Send the request
return $this->call($url, $post_data);
}
//Removes an item from the Solr index
public function removeFromIndex($name)
{
//Build the Solr URL on which we have to post data
$url = $this->solr_url . "/update?commit=true";
//Name of file to delete from index (Build the XML)
$post_data = "<delete><id>" . urlencode($name) . "</id></delete>";
//Send the request
return $this->call($url, $post_data, "Content-type:text/xml; charset=utf-8");
}
public function call($url, $post_data = null, $header = null){
// Initialize cURL
$ch = curl_init();
// Request header
if( $header !== null ){
curl_setopt($ch, CURLOPT_HTTPHEADER, array($header));
}
// Set URL on which you want to post the Form and/or data
curl_setopt($ch, CURLOPT_URL, $url);
// Data+Files to be posted
if($post_data !== null)
{
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
}
// Pass TRUE or 1 if you want to wait for and catch the response against the request made
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
// For Debug mode; shows up any error encountered during the operation
curl_setopt($ch, CURLOPT_VERBOSE, 1);
// Execute the request
return curl_exec($ch);
}
}
@diveyez
Copy link

diveyez commented Sep 22, 2018

Please update

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