How to build a RESTful API? - php

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.

Related

How to Return List of Project Tasks in ActiveCollab

Sorry this may be a trivial question but I am new to PHP. In the documentation to retrieve project tasks, the following code is provided to connect to an Active Collab cloud account:
<?php
require_once '/path/to/vendor/autoload.php';
// Provide name of your company, name of the app that you are developing, your email address and password.
$authenticator = new \ActiveCollab\SDK\Authenticator\Cloud('ACME Inc', 'My Awesome Application', 'you#acmeinc.com', 'hard to guess, easy to remember');
// Show all Active Collab 5 and up account that this user has access to.
print_r($authenticator->getAccounts());
// Show user details (first name, last name and avatar URL).
print_r($authenticator->getUser());
// Issue a token for account #123456789.
$token = $authenticator->issueToken(123456789);
// Did we get it?
if ($token instanceof \ActiveCollab\SDK\TokenInterface) {
print $token->getUrl() . "\n";
print $token->getToken() . "\n";
} else {
print "Invalid response\n";
die();
}
This works fine. I can then create a client to make API calls:
$client = new \ActiveCollab\SDK\Client($token);
and get the list of tasks for a given project as shown in the documentation.
$client->get('projects/65/tasks'); // PHP object
My question is, what methods/attributes are available to get the list of tasks? I can print the object using print_r() (print will obviously not work), and what I really want is in the raw_response header. This is private however and I cannot access it. How do I actually get the list of tasks (ex: the raw_response either has a string or json object)?
Thanks in advance.
There are several methods to work with body:
$response = $client->get('projects/65/tasks');
// Will output raw JSON, as string.
$response->getBody();
// Will output parsed JSON, as associative array.
print_r($response->getJson());
For full list of available response methods, please check ResponseInterface.
If you wish to loop through tasks, use something like this:
$response = $client->get('projects/65/tasks');
$parsed_json = $response->getJson();
if (!empty($parsed_json['tasks'])) {
foreach ($parsed_json['tasks'] as $task) {
print $task['name'] . "\n"
}
}

How can CURL be used to update sql table values in PHP? [duplicate]

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 a rest API i need to parse a forever changing json result

Okay so here goes i am using a rest api called strichliste
i am creating a user credit payment system
i am trying to grab a users balance by username problems is
my restapi i can only get the blanace via its userid
I have created a bit of php that grabs all the current users and the corresponding id and balance using this below
function getbal(){
// Get cURL resource
$curl = curl_init();
// Set some options - we are passing in a useragent too here
curl_setopt_array($curl, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => 'https://example.io:8081/user/'
)
);
// Send the request & save response to $resp
$resp = curl_exec($curl);
// Close request to clear up some resources
curl_close($curl);
print_r($resp);
}
this is the resulting respinse i get after using this in my main php script
<? getbal(); ?>
result --- #
{
"overallCount":3,
"limit":null,
"offset":null,"entries":[
{"id":1,
"name":"admin",
"balance":0,
"lastTransaction":null
},
{"id":2,
"name":"pghost",
"balance":0,
"lastTransaction":null
},
{"id":3,
"name":"sanctum",
"balance":0,
"lastTransaction":null
}
]
}
as you can see there are only currently 3 users but this will grow everyday so the script needs to adapt to growing numbers of users
inside my php script i have a var with the currently logged in use so example
$user = "sanctum";
i want a php script that will use the output fro gatbal(); and only output the line for the given user in this case sanctum
i want it to output the line in jsondecode for the specific user
{"id":3,"name":"sanctum","balance":0,"lastTransaction":null}
can anyone help
$user = "sanctum";
$userlist = getbal();
function findUser($u, $l){
if(!empty($l['entries'])){
foreach($l['entries'] as $key=>$val){
if($val['name']==$user){
return $val;
}
}
}
}
This way, once you have the list, and the user, you can just invoke findUser() by plugging in the userlist, and the user.
$userData = findUser($user, $userlist);
However, I would suggest finding a way to get the server to return only the user you are looking for, instead of the whole list, and then finding based on username. But thats another discussion for another time.

Instagram Real time API - PHP - Unable to get POST Update

I'm trying to connect with the instagram API, the connection works fine and I am receiving the updates just as described in the API documentation, the issue is that I cannot access to the data send to my callback function.
According to the doc
When someone posts a new photo and it triggers an update of one of your subscriptions, we make a POST request to the callback URL that you defined in the subscription
This is my code :
// check if we have a security challenge
if (isset ($_GET['hub_challenge']))
echo $_GET['hub_challenge'];
else // This is an update
{
// read the content of $_POST
$myString = file_get_contents('php://input');
$answer = json_decode($myString);
// This is not working starting from here
$id = $answer->{'object_id'};
$api = 'https://api.instagram.com/v1/locations/'.$id.'/media/recent?client_secret='.INSTA_CLI_SECRET.'&client_id='.INSTA_CLI_ID;
$response = get_curl($api); //change request path to pull different photos
$images = array();
if($response){
$decode = json_decode($response);
foreach($decode->{'data'} as $item){
// do something with the data here
}
}
}
Displaying the $myString variable I have this result, don't know why it is not decoded to json :(
[{"changed_aspect": "media", "subscription_id": 2468174, "object":
"geography", "object_id": "1518250", "time": 1350044500}]
the get_curl function is working fine when I hardcode my $id.
I guess something is wrong with my $myString, unfortunately the $_POST cvariable is not populated, Any idea what I am missing ?
Looking at the example JSON response included in your question, I can conclude that the object you are trying to talk with is wrapped in an array (hence the [ and ] around it in the JSON string).
You should access it using $answers[0]->object_id.
If that doesn't work, you can always use var_dump to check out the data in one of your variables.

Is there a way to download bibtex from Google Scholar using PHP

Hi, is there a way to download the BibTeX entry for something from Google Scholar using PHP without having to download the BibTeX manually one by one? For example, setting a search value like "research" and then downloading the related BibTeX from the links automatically through code.
Any help would be appreciated. I tried to get the HTML page, but as I try to get the page contents the "Import to BibTeX" link disappears on the retrieved page contents.
My code:
<?php
$url = 'http://scholar.google.com/scholar?q=honors+college&hl=en&btnG=Search& amp;as_sdt=1%2C4&as_sdtp=on';
$needle = 'Import into bibtex';
$contents = file_get_contents($url);
echo $contents;
if(strpos($contents, $needle)!== false) {
echo 'found';
} else {
echo 'not found';
}
?>
The short answer is No you cannot do this
Google does not provide API's for search / scholar and uses firm rate-limitation. The problem is that for each BibTex entry you need 2 additional requests (1 for the query, 1 for the 'import link' and a final one to get the actual BibTex entry content)
I wrote a script that scrapes google scholar results and finds the BibTex links and saves the results. However, due to the rate limit is not viable and will get blocked almost instantly.
Code can be viewed here: https://gist.github.com/Tessmore/11099509 and is free of use, but at your own risk.
As Tessmore said - you can't. But you can make it work by using Google Scholar Organic Results API from SerpApi that bypasses quota limits and blocks from search engines so you don't have to think about how to reduce the chance of being blocked.
Example:
Install google-search-results-php package first via composer:
$ composer require serpapi/google-search-results-php:2.0
Code to integrate and full example in the online IDE:
<?php
ini_set("display_errors", 1);
ini_set("display_startup_errors", 1);
error_reporting(E_ALL);
require __DIR__ . "/vendor/autoload.php";
function getResultIds () {
$result_ids = array();
$params = [
"engine" => "google_scholar", // parsing engine
"q" => "biology" // search query
];
$search = new GoogleSearch(getenv("API_KEY"));
$response = $search->get_json($params);
foreach ($response->organic_results as $result) {
// print_r($result->result_id);
array_push($result_ids, $result->result_id);
}
return $result_ids;
}
function getBibtexData () {
$bibtex_data = array();
foreach (getResultIds() as $result_id) {
$params = [
"engine" => "google_scholar_cite", // parsing engine
"q" => $result_id
];
$search = new GoogleSearch(getenv("API_KEY"));
$response = $search->get_json($params);
foreach ($response->links as $result) {
if ($result->name === "BibTeX") {
array_push($bibtex_data, $result->link);
}
}
}
return $bibtex_data;
}
print_r(json_encode(getBibtexData(), JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES));
?>
Output:
[
"https://scholar.googleusercontent.com/scholar.bib?q=info:KNJ0p4CbwgoJ:scholar.google.com/&output=citation&scisdr=CgXjqB_WGAA:AAGBfm0AAAAAYkm8amenawYn_EBidiCQT5QBh0L1KJEX&scisig=AAGBfm0AAAAAYkm8at9X4P3eIWKUCOc6UriCEDKVsQE0&scisf=4&ct=citation&cd=-1&hl=en",
"https://scholar.googleusercontent.com/scholar.bib?q=info:6zRLFbcxtREJ:scholar.google.com/&output=citation&scisdr=CgWhqfi6GAA:AAGBfm0AAAAAYkm8bDoIhTlfTkQFCOzYGax54Bst576o&scisig=AAGBfm0AAAAAYkm8bMe_7Nq4e4pB5lg_eR9jmeGrO8ek&scisf=4&ct=citation&cd=-1&hl=en",
"https://scholar.googleusercontent.com/scholar.bib?q=info:6Yb0qOX88FMJ:scholar.google.com/&output=citation&scisdr=CgXn_4MdGAA:AAGBfm0AAAAAYkm8bi8ypCZcFDNEQZYZeoSlvx-U1OSk&scisig=AAGBfm0AAAAAYkm8bnFMnwTWGfkfJDCNEx0C4n-aQwql&scisf=4&ct=citation&cd=-1&hl=en",
"https://scholar.googleusercontent.com/scholar.bib?q=info:HFdEElNr3IgJ:scholar.google.com/&output=citation&scisdr=CgXKCFpQGAA:AAGBfm0AAAAAYkm8byukcQCl4WHQx-nSNp2pC1gUFSKG&scisig=AAGBfm0AAAAAYkm8b8EReTVkLwtxfth_pjwMyyY3dqts&scisf=4&ct=citation&cd=-1&hl=en",
"https://scholar.googleusercontent.com/scholar.bib?q=info:bs-D_MeC14YJ:scholar.google.com/&output=citation&scisdr=CgXEUXwWGAA:AAGBfm0AAAAAYkm8bwwfMNJrffe16EaGypsem9JlmGTi&scisig=AAGBfm0AAAAAYkm8b6nWlPOQL63fXg6dV2U-JQbpyQyS&scisf=4&ct=citation&cd=-1&hl=en",
"https://scholar.googleusercontent.com/scholar.bib?q=info:Rn1qFVLRfKwJ:scholar.google.com/&output=citation&scisdr=CgU-HswkGAA:AAGBfm0AAAAAYkm8cHE1YRK23eHV8nzF89Eem-Bsuz72&scisig=AAGBfm0AAAAAYkm8cDEj8ZrzZjAo2bNX-tjYYYJYQZay&scisf=4&ct=citation&cd=-1&hl=en",
"https://scholar.googleusercontent.com/scholar.bib?q=info:d8thHtTwq6YJ:scholar.google.com/&output=citation&scisdr=CgXj7oe9GAA:AAGBfm0AAAAAYkm8cTYamCKGKImjdg5MQdgbxUIIHAEY&scisig=AAGBfm0AAAAAYkm8cTcop1ceKzKYvKAKtvlSQ1EdEtSN&scisf=4&ct=citation&cd=-1&hl=en",
"https://scholar.googleusercontent.com/scholar.bib?q=info:IUmhOhGaDaEJ:scholar.google.com/&output=citation&scisdr=CgU0qZ2_GAA:AAGBfm0AAAAAYkm8ctCPwoihZkjbNcdEqSnwa0J3jwDy&scisig=AAGBfm0AAAAAYkm8cingBcYnEp8YRqFDFdN-FAEBgDT7&scisf=4&ct=citation&cd=-1&hl=en",
"https://scholar.googleusercontent.com/scholar.bib?q=info:PWsf8O5OMQEJ:scholar.google.com/&output=citation&scisdr=CgVBAJxXGAA:AAGBfm0AAAAAYkm8c3CDKQG0Wh_lWsXU_DZxEJkwZz5y&scisig=AAGBfm0AAAAAYkm8c6I-HjAxD1Gy6FLFDRdxH_qU4OBr&scisf=4&ct=citation&cd=-1&hl=en",
"https://scholar.googleusercontent.com/scholar.bib?q=info:yGvgHH8ROuIJ:scholar.google.com/&output=citation&scisdr=CgXFuhOkGAA:AAGBfm0AAAAAYkm8dD0rcSR4LQF8GgTxx865BADtXNDN&scisig=AAGBfm0AAAAAYkm8dIQhodz3rHF9IUdaCSRlhdudACNQ&scisf=4&ct=citation&cd=-1&hl=en"
]
Bibtex data from the first URL:
#article{woese2004new,
title={A new biology for a new century},
author={Woese, Carl R},
journal={Microbiology and molecular biology reviews},
volume={68},
number={2},
pages={173--186},
year={2004},
publisher={Am Soc Microbiol}
}
Disclaimer, I work for SerpApi.

Categories