I have been searching around for examples but the documentation on:
http://php.net/manual/en/solrclient.query.php
and
https://www.ayalon.ch/en/code-samples/solr-php-client-example
does not give me enough information to alter for my setup.
I am trying to execute a solr query using php from my website.
The search box form method is post and the input name is q.
This is all of the php I have at the moment; I was testing the connection.
<?php
require_once('C:\Program Files\Solr\solr-7.5.0\dist\solr-php-client-master\Apache\Solr\Service.php');
$client = new Apache_Solr_Service( 'localhost', '8983', '/solr/#/sqltest' );
if ( ! $client->ping() ) {
echo 'Solr service not up dude.';
}
else{
echo 'ayee we have a connection here!';
}
//to view the specifics of this setup use
//var_dump($client);
?>
Being new to php, Im really trying to find the proper way to perform the search and display the default json response.
I already have documents indexed to search so my code does not need to add any docs as seen in some of the above tutorials.
When I use this code:
$query = new SolrQuery();
$query->setQuery('lucene');
$query->setStart(0);
$query->setRows(10);
$query->addField('id')->addField('date')->addField('Problem')->addField('Solution');
$query_response = $client->query($query);
$response = $query_response->getResponse();
print_r($response);
I get an error because the class SolrQuery is not found.
Related
I am trying to run the following code with the new Google Business Profile API:
$mybusinessbusinessinformationService = new Google\Service\MyBusinessBusinessInformation($client);
try
{
$locations = $mybusinessbusinessinformationService->accounts_locations->call('list',['parent'=>'accounts/1111111111111111111']);
var_dump($locations);
} catch(Exception $e){
var_dump(print_r($e->getMessage(),1));
}
But I am getting the following error:
(list) missing required param: 'parent'
As far as I can tell it seems that I am parsing the param properly.
For people that are searching for an answer:
Since Google updated its API, it's a requirement to parse readMask as well:
$mybusinessbusinessinformationService = new Google\Service\MyBusinessBusinessInformation($client);
$params = array('readMask'=> "title,name");
$locations = $mybusinessbusinessinformationService->accounts_locations->listAccountsLocations($getAccountName,$params);
var_dump($locations);
You can find the mask parameters here:
https://developers.google.com/my-business/reference/businessinformation/rest/v1/locations
Attemping to post PHP form data from another PHP file to a SOAP wsdl based on if statement of one of the criteria. I cannot get his to work for the life of me. I am new so I know I make many mistakes.
if ( isset( $_GET['submit'] ) ){
$INPUT_STATE=$_GET['INPUT_STATE'];
$SHIP_FROM_STATE = $_GET['SHIP_FROM_STATE'];
$SHIP_FROM_ADDRESS= $_GET['SHIP_FROM_ADDRESS'];
$SHIP_FROM_CITY= $_GET['SHIP_FROM_CITY'];
$SHIP_FROM_ZIP= $_GET['SHIP_FROM_ZIP'];
if ($SHIP_FROM_STATE=='CA');
require_once('C:\xampp\htdocs\addemp\Tax\nusoap.php');
$wsdl = 'http://services.gis.boe.ca.gov/api/taxrates/rates.svc?wsdl';
$server = new SoapClient ($wsdl);
$params= SoapFunction(array(
'StreetAddress'=> $SHIP_FROM_ADDRESS,
'City'=>$SHIP_FROM_CITY,
'ZipCode'=> $SHIP_FROM_ZIP));
$result = $server->call('GetRate', $params);
print_r($result);
}ELSE
The issue is this:
I have a web application that runs on a PHP server. I'd like to build a REST api for it.
I did some research and I figured out that REST api uses HTTP methods (GET, POST...) for certain URI's with an authentication key (not necessarily) and the information is presented back as a HTTP response with the info as XML or JSON (I'd rather JSON).
My question is:
How do I, as the developer of the app, build those URI's? Do I need to write a PHP code at that URI?
How do I build the JSON objects to return as a response?
Here is a very simply example in simple php.
There are 2 files client.php & api.php. I put both files on the same url : http://localhost:8888/, so you will have to change the link to your own url. (the file can be on two different servers).
This is just an example, it's very quick and dirty, plus it has been a long time since I've done php. But this is the idea of an api.
client.php
<?php
/*** this is the client ***/
if (isset($_GET["action"]) && isset($_GET["id"]) && $_GET["action"] == "get_user") // if the get parameter action is get_user and if the id is set, call the api to get the user information
{
$user_info = file_get_contents('http://localhost:8888/api.php?action=get_user&id=' . $_GET["id"]);
$user_info = json_decode($user_info, true);
// THAT IS VERY QUICK AND DIRTY !!!!!
?>
<table>
<tr>
<td>Name: </td><td> <?php echo $user_info["last_name"] ?></td>
</tr>
<tr>
<td>First Name: </td><td> <?php echo $user_info["first_name"] ?></td>
</tr>
<tr>
<td>Age: </td><td> <?php echo $user_info["age"] ?></td>
</tr>
</table>
Return to the user list
<?php
}
else // else take the user list
{
$user_list = file_get_contents('http://localhost:8888/api.php?action=get_user_list');
$user_list = json_decode($user_list, true);
// THAT IS VERY QUICK AND DIRTY !!!!!
?>
<ul>
<?php foreach ($user_list as $user): ?>
<li>
<a href=<?php echo "http://localhost:8888/client.php?action=get_user&id=" . $user["id"] ?> alt=<?php echo "user_" . $user_["id"] ?>><?php echo $user["name"] ?></a>
</li>
<?php endforeach; ?>
</ul>
<?php
}
?>
api.php
<?php
// This is the API to possibility show the user list, and show a specific user by action.
function get_user_by_id($id)
{
$user_info = array();
// make a call in db.
switch ($id){
case 1:
$user_info = array("first_name" => "Marc", "last_name" => "Simon", "age" => 21); // let's say first_name, last_name, age
break;
case 2:
$user_info = array("first_name" => "Frederic", "last_name" => "Zannetie", "age" => 24);
break;
case 3:
$user_info = array("first_name" => "Laure", "last_name" => "Carbonnel", "age" => 45);
break;
}
return $user_info;
}
function get_user_list()
{
$user_list = array(array("id" => 1, "name" => "Simon"), array("id" => 2, "name" => "Zannetie"), array("id" => 3, "name" => "Carbonnel")); // call in db, here I make a list of 3 users.
return $user_list;
}
$possible_url = array("get_user_list", "get_user");
$value = "An error has occurred";
if (isset($_GET["action"]) && in_array($_GET["action"], $possible_url))
{
switch ($_GET["action"])
{
case "get_user_list":
$value = get_user_list();
break;
case "get_user":
if (isset($_GET["id"]))
$value = get_user_by_id($_GET["id"]);
else
$value = "Missing argument";
break;
}
}
exit(json_encode($value));
?>
I didn't make any call to the database for this example, but normally that is what you should do. You should also replace the "file_get_contents" function by "curl".
In 2013, you should use something like Silex or Slim
Silex example:
require_once __DIR__.'/../vendor/autoload.php';
$app = new Silex\Application();
$app->get('/hello/{name}', function($name) use($app) {
return 'Hello '.$app->escape($name);
});
$app->run();
Slim example:
$app = new \Slim\Slim();
$app->get('/hello/:name', function ($name) {
echo "Hello, $name";
});
$app->run();
That is pretty much the same as created a normal website.
Normal pattern for a php website is:
The user enter a url
The server get the url, parse it and execute a action
In this action, you get/generate every information you need for the page
You create the html/php page with the info from the action
The server generate a fully html page and send it back to the user
With a api, you just add a new step between 3 and 4. After 3, create a array with all information you need. Encode this array in json and exit or return this value.
$info = array("info_1" => 1; "info_2" => "info_2" ... "info_n" => array(1,2,3));
exit(json_encode($info));
That all for the api.
For the client side, you can call the api by the url. If the api work only with get call, I think it's possible to do a simply (To check, I normally use curl).
$info = file_get_contents(url);
$info = json_decode($info);
But it's more common to use the curl library to perform get and post call.
You can ask me if you need help with curl.
Once the get the info from the api, you can do the 4 & 5 steps.
Look the php doc for json function and file_get_contents.
curl : http://fr.php.net/manual/fr/ref.curl.php
EDIT
No, wait, I don't get it. "php API page" what do you mean by that ?
The api is only the creation/recuperation of your project. You NEVER send directly the html result (if you're making a website) throw a api. You call the api with the url, the api return information, you use this information to create the final result.
ex: you want to write a html page who say hello xxx. But to get the name of the user, you have to get the info from the api.
So let's say your api have a function who have user_id as argument and return the name of this user (let's say getUserNameById(user_id)), and you call this function only on a url like your/api/ulr/getUser/id.
Function getUserNameById(user_id)
{
$userName = // call in db to get the user
exit(json_encode($userName)); // maybe return work as well.
}
From the client side you do
$username = file_get_contents(your/api/url/getUser/15); // You should normally use curl, but it simpler for the example
// So this function to this specifique url will call the api, and trigger the getUserNameById(user_id), whom give you the user name.
<html>
<body>
<p>hello <?php echo $username ?> </p>
</body>
</html>
So the client never access directly the databases, that the api's role.
Is that clearer ?
(1) How do I ... build those URI's? Do I need to write a PHP code at that URI?
There is no standard for how an API URI scheme should be set up, but it's common to have slash-separated values. For this you can use...
$apiArgArray = explode("/", substr(#$_SERVER['PATH_INFO'], 1));
...to get an array of slash-separated values in the URI after the file name.
Example: Assuming you have an API file api.php in your application somewhere and you do a request for api.php/members/3, then $apiArgArray will be an array containing ['members', '3']. You can then use those values to query your database or do other processing.
(2) How do I build the JSON objects to return as a response?
You can take any PHP object and turn it into JSON with json_encode. You'll also want to set the appropriate header.
header('Content-Type: application/json');
$myObject = (object) array( 'property' => 'value' ); // example
echo json_encode($myObject); // outputs JSON text
All this is good for an API that returns JSON, but the next question you should ask is:
(3) How do I make my API RESTful?
For that we'll use $_SERVER['REQUEST_METHOD'] to get the method being used, and then do different things based on that. So the final result is something like...
header('Content-Type: application/json');
$apiArgArray = explode("/", substr(#$_SERVER['PATH_INFO'], 1));
$returnObject = (object) array();
/* Based on the method, use the arguments to figure out
whether you're working with an individual or a collection,
then do your processing, and ultimately set $returnObject */
switch ($_SERVER['REQUEST_METHOD']) {
case 'GET':
// List entire collection or retrieve individual member
break;
case 'PUT':
// Replace entire collection or member
break;
case 'POST':
// Create new member
break;
case 'DELETE':
// Delete collection or member
break;
}
echo json_encode($returnObject);
Sources: https://stackoverflow.com/a/897311/1766230 and http://en.wikipedia.org/wiki/Representational_state_transfer#Applied_to_web_services
Another framework which has not been mentioned so far is Laravel. It's great for building PHP apps in general but thanks to the great router it's really comfortable and simple to build rich APIs. It might not be that slim as Slim or Sliex but it gives you a solid structure.
See Aaron Kuzemchak - Simple API Development With Laravel on YouTube and
Laravel 4: A Start at a RESTful API on NetTuts+
I know that this question is accepted and has a bit of age but this might be helpful for some people who still find it relevant. Although the outcome is not a full RESTful API the API Builder mini lib for PHP allows you to easily transform MySQL databases into web accessible JSON APIs.
As simon marc said, the process is much the same as it is for you or I browsing a website. If you are comfortable with using the Zend framework, there are some easy to follow tutorials to that make life quite easy to set things up. The hardest part of building a restful api is the design of the it, and making it truly restful, think CRUD in database terms.
It could be that you really want an xmlrpc interface or something else similar. What do you want this interface to allow you to do?
--EDIT
Here is where I got started with restful api and Zend Framework.
Zend Framework Example
In short don't use Zend rest server, it's obsolete.
I am using the PHP Toolkit (v20) with the Enterprise WSDL to access my Salesforce objects and records in my webapp.
I successfully got everything working on my localhost.
When I uploaded the script to my webhost (inmotion), the create function simply does not work. It does not show any errors or warnings (although I have set error reporting to E_ALL), but execution of the script simply stops when it encounters the create function.
However, running a query using the query function or something like getting the server timestamp works fine.
Again, it works fine on my localhost, so I dont think its a code problem, but for the life of me I cannot figure out the problem, as no errors/warnings are displayed nor exceptions thrown.
I should clarify that although in this example I am trying to insert into my custom object, I have tried to insert into a standard Account or Contact object as well and it has not made any difference.
It will be great if somebody can guide me on how I can go about trying to troubleshoot the problem.
Thanks.
Code is as follows:
<html>
<head></head>
<body>
<?php
ini_set("soap.wsdl_cache_enabled", "0");
define("USERNAME", "myusername");
define("PASSWORD", "mypassword");
define("SECURITY_TOKEN", "mysecuritytoken");
require_once ('soapclient/SforceEnterpriseClient.php');
try {
$sflink = new SforceEnterpriseClient();
$sflink->createConnection("soapclient/auv.wsdl.xml",null,array('trace'=>true));
//$sflink->createConnection("soapclient/auv.wsdl.xml");
$sflink->login(USERNAME, PASSWORD.SECURITY_TOKEN);
// Test to get the server timestamp - Works fine.
echo "Getting Timestamp<br>";
$resp = $sflink->getServerTimestamp();
print_r($resp);
echo "<br>";
// Test to query the server - Works fine.
$query = "SELECT Id, AccountId, FirstName, LastName FROM Contact WHERE Email = 'ankur#alfauv.com'";
$response = $sflink->query($query);
echo "Select result is: <br>";
print_r($response);
echo "<br>";
// Insert into UVSI Search Object (My custom object) - Does not work
$sObject = new stdclass();
$sObject->Account__c = "00190000006yxUrAAI";
$sObject->Contact__c = "00390000005ZYLcAAO";
$sObject->Application__c = "AAP";
$sObject->Flow__c = 66;
$sObject->Flow_Unit__c = "m3-hr";
$sObject->Dose__c = 33;
$sObject->UVT__c = 99;
echo "Attempting creation<br>";
$createResponse = $sflink->create(array($sObject), 'UVSI_Search__c');
echo "This line never prints.<br/>";
} catch (Exception $e) {
echo "In error condition<br>";
echo $sflink->getLastRequest();
echo $e->faultstring;
exit();
}
?>
</body>
</html>
After breaking my head over this for 3 days, I finally found a solution. I changed the PHP version for my site from 5.2 to 5.3 and the problem just went away.
I still dont know why it did not work, but this is the solution in case anybody else has a similar problem.
The issue is this:
I have a web application that runs on a PHP server. I'd like to build a REST api for it.
I did some research and I figured out that REST api uses HTTP methods (GET, POST...) for certain URI's with an authentication key (not necessarily) and the information is presented back as a HTTP response with the info as XML or JSON (I'd rather JSON).
My question is:
How do I, as the developer of the app, build those URI's? Do I need to write a PHP code at that URI?
How do I build the JSON objects to return as a response?
Here is a very simply example in simple php.
There are 2 files client.php & api.php. I put both files on the same url : http://localhost:8888/, so you will have to change the link to your own url. (the file can be on two different servers).
This is just an example, it's very quick and dirty, plus it has been a long time since I've done php. But this is the idea of an api.
client.php
<?php
/*** this is the client ***/
if (isset($_GET["action"]) && isset($_GET["id"]) && $_GET["action"] == "get_user") // if the get parameter action is get_user and if the id is set, call the api to get the user information
{
$user_info = file_get_contents('http://localhost:8888/api.php?action=get_user&id=' . $_GET["id"]);
$user_info = json_decode($user_info, true);
// THAT IS VERY QUICK AND DIRTY !!!!!
?>
<table>
<tr>
<td>Name: </td><td> <?php echo $user_info["last_name"] ?></td>
</tr>
<tr>
<td>First Name: </td><td> <?php echo $user_info["first_name"] ?></td>
</tr>
<tr>
<td>Age: </td><td> <?php echo $user_info["age"] ?></td>
</tr>
</table>
Return to the user list
<?php
}
else // else take the user list
{
$user_list = file_get_contents('http://localhost:8888/api.php?action=get_user_list');
$user_list = json_decode($user_list, true);
// THAT IS VERY QUICK AND DIRTY !!!!!
?>
<ul>
<?php foreach ($user_list as $user): ?>
<li>
<a href=<?php echo "http://localhost:8888/client.php?action=get_user&id=" . $user["id"] ?> alt=<?php echo "user_" . $user_["id"] ?>><?php echo $user["name"] ?></a>
</li>
<?php endforeach; ?>
</ul>
<?php
}
?>
api.php
<?php
// This is the API to possibility show the user list, and show a specific user by action.
function get_user_by_id($id)
{
$user_info = array();
// make a call in db.
switch ($id){
case 1:
$user_info = array("first_name" => "Marc", "last_name" => "Simon", "age" => 21); // let's say first_name, last_name, age
break;
case 2:
$user_info = array("first_name" => "Frederic", "last_name" => "Zannetie", "age" => 24);
break;
case 3:
$user_info = array("first_name" => "Laure", "last_name" => "Carbonnel", "age" => 45);
break;
}
return $user_info;
}
function get_user_list()
{
$user_list = array(array("id" => 1, "name" => "Simon"), array("id" => 2, "name" => "Zannetie"), array("id" => 3, "name" => "Carbonnel")); // call in db, here I make a list of 3 users.
return $user_list;
}
$possible_url = array("get_user_list", "get_user");
$value = "An error has occurred";
if (isset($_GET["action"]) && in_array($_GET["action"], $possible_url))
{
switch ($_GET["action"])
{
case "get_user_list":
$value = get_user_list();
break;
case "get_user":
if (isset($_GET["id"]))
$value = get_user_by_id($_GET["id"]);
else
$value = "Missing argument";
break;
}
}
exit(json_encode($value));
?>
I didn't make any call to the database for this example, but normally that is what you should do. You should also replace the "file_get_contents" function by "curl".
In 2013, you should use something like Silex or Slim
Silex example:
require_once __DIR__.'/../vendor/autoload.php';
$app = new Silex\Application();
$app->get('/hello/{name}', function($name) use($app) {
return 'Hello '.$app->escape($name);
});
$app->run();
Slim example:
$app = new \Slim\Slim();
$app->get('/hello/:name', function ($name) {
echo "Hello, $name";
});
$app->run();
That is pretty much the same as created a normal website.
Normal pattern for a php website is:
The user enter a url
The server get the url, parse it and execute a action
In this action, you get/generate every information you need for the page
You create the html/php page with the info from the action
The server generate a fully html page and send it back to the user
With a api, you just add a new step between 3 and 4. After 3, create a array with all information you need. Encode this array in json and exit or return this value.
$info = array("info_1" => 1; "info_2" => "info_2" ... "info_n" => array(1,2,3));
exit(json_encode($info));
That all for the api.
For the client side, you can call the api by the url. If the api work only with get call, I think it's possible to do a simply (To check, I normally use curl).
$info = file_get_contents(url);
$info = json_decode($info);
But it's more common to use the curl library to perform get and post call.
You can ask me if you need help with curl.
Once the get the info from the api, you can do the 4 & 5 steps.
Look the php doc for json function and file_get_contents.
curl : http://fr.php.net/manual/fr/ref.curl.php
EDIT
No, wait, I don't get it. "php API page" what do you mean by that ?
The api is only the creation/recuperation of your project. You NEVER send directly the html result (if you're making a website) throw a api. You call the api with the url, the api return information, you use this information to create the final result.
ex: you want to write a html page who say hello xxx. But to get the name of the user, you have to get the info from the api.
So let's say your api have a function who have user_id as argument and return the name of this user (let's say getUserNameById(user_id)), and you call this function only on a url like your/api/ulr/getUser/id.
Function getUserNameById(user_id)
{
$userName = // call in db to get the user
exit(json_encode($userName)); // maybe return work as well.
}
From the client side you do
$username = file_get_contents(your/api/url/getUser/15); // You should normally use curl, but it simpler for the example
// So this function to this specifique url will call the api, and trigger the getUserNameById(user_id), whom give you the user name.
<html>
<body>
<p>hello <?php echo $username ?> </p>
</body>
</html>
So the client never access directly the databases, that the api's role.
Is that clearer ?
(1) How do I ... build those URI's? Do I need to write a PHP code at that URI?
There is no standard for how an API URI scheme should be set up, but it's common to have slash-separated values. For this you can use...
$apiArgArray = explode("/", substr(#$_SERVER['PATH_INFO'], 1));
...to get an array of slash-separated values in the URI after the file name.
Example: Assuming you have an API file api.php in your application somewhere and you do a request for api.php/members/3, then $apiArgArray will be an array containing ['members', '3']. You can then use those values to query your database or do other processing.
(2) How do I build the JSON objects to return as a response?
You can take any PHP object and turn it into JSON with json_encode. You'll also want to set the appropriate header.
header('Content-Type: application/json');
$myObject = (object) array( 'property' => 'value' ); // example
echo json_encode($myObject); // outputs JSON text
All this is good for an API that returns JSON, but the next question you should ask is:
(3) How do I make my API RESTful?
For that we'll use $_SERVER['REQUEST_METHOD'] to get the method being used, and then do different things based on that. So the final result is something like...
header('Content-Type: application/json');
$apiArgArray = explode("/", substr(#$_SERVER['PATH_INFO'], 1));
$returnObject = (object) array();
/* Based on the method, use the arguments to figure out
whether you're working with an individual or a collection,
then do your processing, and ultimately set $returnObject */
switch ($_SERVER['REQUEST_METHOD']) {
case 'GET':
// List entire collection or retrieve individual member
break;
case 'PUT':
// Replace entire collection or member
break;
case 'POST':
// Create new member
break;
case 'DELETE':
// Delete collection or member
break;
}
echo json_encode($returnObject);
Sources: https://stackoverflow.com/a/897311/1766230 and http://en.wikipedia.org/wiki/Representational_state_transfer#Applied_to_web_services
Another framework which has not been mentioned so far is Laravel. It's great for building PHP apps in general but thanks to the great router it's really comfortable and simple to build rich APIs. It might not be that slim as Slim or Sliex but it gives you a solid structure.
See Aaron Kuzemchak - Simple API Development With Laravel on YouTube and
Laravel 4: A Start at a RESTful API on NetTuts+
I know that this question is accepted and has a bit of age but this might be helpful for some people who still find it relevant. Although the outcome is not a full RESTful API the API Builder mini lib for PHP allows you to easily transform MySQL databases into web accessible JSON APIs.
As simon marc said, the process is much the same as it is for you or I browsing a website. If you are comfortable with using the Zend framework, there are some easy to follow tutorials to that make life quite easy to set things up. The hardest part of building a restful api is the design of the it, and making it truly restful, think CRUD in database terms.
It could be that you really want an xmlrpc interface or something else similar. What do you want this interface to allow you to do?
--EDIT
Here is where I got started with restful api and Zend Framework.
Zend Framework Example
In short don't use Zend rest server, it's obsolete.