Created
September 29, 2012 05:12
-
-
Save twhitney11/3803240 to your computer and use it in GitHub Desktop.
Simple Solr Interfacing PHP Class
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Please update