I'm using the twitter api to get my latest mentions.
Twitter api link: https://dev.twitter.com/rest/reference/get/statuses/mentions_timeline
Function used to get last mentions:
function twitter_get_tweets(){
$connection = $this->twitter_auth();
$latest_tweet = $connection->get('statuses/mentions_timeline', array('count' => 1));
return $latest_tweet;
}
Preview of response: http://projects.helpful.ninja/twitter/
Sadly im not able to access the variables in there directly, such as the text node.
Example:
[text] => #pr0b_ Submit a request to our Support team and they'll be in touch ASAP
Been testing something like:
$twitter_bot = new twitter_bot_functions($twitter_settings['api_key'], $twitter_settings['api_secret'], $twitter_settings['access_token'], $twitter_settings['access_token_secret']);
$get_latest_mention = $twitter_bot->twitter_get_tweets();
echo $get_latest_mention['text'];
Does someone have a idea what I'm doing wrong?
It is an array first and then a stdClass object. So you should use it like
echo $get_latest_mention[0]->text;
Related
I am using https://github.com/BingAds/BingAds-PHP-SDK to send offline conversion data to Bing. I am successfully able to connect and call different service using OATH. But when I am trying to send offline conversion request I am failed. Bing SOAP request's example for Offline conversion requests https://msdn.microsoft.com/en-us/library/bing-ads-campaign-management-applyofflineconversions.aspx
Now, I need help from you guys, If I want to send ApplyOfflineConversionsRequest what approach should I use SoapVar and then CampaignManagement ApplyOfflineConversions? I am asking this because I am not very well known about the Bing API v11.
After my proper OATH process
//Setting the account id as CustomerAccountId in the header element as per Bing API Doc
$GLOBALS['AuthorizationData']->AccountId = $obj->Id;
//send offline conversion
$offline = new OfflineConversion();
$offline->ConversionCurrencyCode = 'USD';
$offline->ConversionName = 'OfflineConversionSellOfRentals';
$offline->ConversionTime = date('Y-m-d\TH:i:s', strtotime('-7 days'));
$offline->ConversionValue = 2.5;
$offline->MicrosoftClickId = '8349a6501442491186ce602ca56881fe';
$offline_response = new SoapVar($offline, SOAP_ENC_OBJECT, 'OfflineConversion', $GLOBALS['CampaignProxy']->GetNamespace());
$request[] = $offline_response;
$offline_response = CampaignManagementHelper::ApplyOfflineConversions($request);
print_r($offline_response);
I have created a static method inside CampaignManagementHelper.php file because I didn't find any implementation of AddOfflineConversion method on the Bing API SDK.
static function AddOfflineConversion($offline){
$GLOBALS['Proxy'] = $GLOBALS['CampaignProxy'];
$request = new ApplyOfflineConversionsRequest();
$request->OfflineConversions[] = $offline;
return $GLOBALS['CampaignProxy']->GetService()->ApplyOfflineConversions($request);
}
I am able to import offline CSV conversion that means My UET Tags and Conversion Goal are enabled.
I am having a hard time because I didn't get any sample example for how to request for offline conversion requests.
Response from Bing API call:
stdClass Object
(
[PartialErrors] => stdClass Object
(
)
)
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 managing vApps via the vCloud API(1.5) and the vCloud PHP SDK(1.5).
I can start a stopped VM using the following below, however I am not sure how you can stop a running/deployed VM while reading the documentation. I see that you can invoke an action/powerOff, however I am not sure how you would do it within the SDK. Any help is appreciated!
<?php
// This will start/turn on a vApp/VM. However, I cannot figure out how to turn it off from reading the documentation using the PHP SDK. Any help is appreciated!
// login
$service = VMware_VCloud_SDK_Service::getService();
$service->login($server, array('username'=>$user, 'password'=>$pswd), $httpConfig);
// create an SDK Org object
$orgRefs = $service->getOrgRefs($orgName);
if (0 == count($orgRefs))
{
exit("No organization with name $orgName is found\n");
}
$orgRef = $orgRefs[0];
$sdkOrg = $service->createSDKObj($orgRef);
// create an SDK vDC object
$vdcRefs = $sdkOrg->getVdcRefs($vdcName);
if (0 == count($vdcRefs))
{
exit("No vDC with name $vdcName is found\n");
}
$vdcRef = $vdcRefs[0];
$sdkVdc = $service->createSDKObj($vdcRef);
// get a reference to a vApp in the vDC
$vAppRefs = $sdkVdc->getVAppRefs($vAppName);
if (!$vAppRefs)
{
exit("No vApp with name $vAppName is found\n");
}
$vAppRef = $vAppRefs[0];
// create an SDK vApp object
$sdkVApp = $service->createSDKObj($vAppRef);
// create a VMware_VCloud_API_DeployVAppParamsType data object
$params = new VMware_VCloud_API_DeployVAppParamsType();
$params->set_powerOn($powerOn);
$params->set_deploymentLeaseSeconds($deploymentLeaseSeconds);
// deploy the vApp
$sdkVApp->deploy($params)
<?php
References:
vCloud API Programming Guide
: http://vmware.com/pdf/vcd_15_api_guide.pdf
vCloud SDK for PHP Developer's Guide : http://www.vmware.com/pdf/vcd_15_sdk_php_dg.pdf
Use your $sdkVApp object:
$sdkVApp->powerOff();
Your $sdkVApp is of type VMware_VCloud_SDK_VApp.
The powerOff function is defined in the parent abstract class VMWare_VCloud_SDK_VApp_Abstract. There are other functions in this abstract class such as suspend(), powerOn(), reset(), etc.
The only thing I could not figure out yet is when using the powerOff() or suspend() function, the VApp gets powered Off or Suspended (shown in vCenter) but vCD shows the VM partially powered-off/suspended and the VApp still show Running.
Just found the reason why we see the partially powered-off/suspended.
We need to use the undeploy() function...
http://blogs.vmware.com/vsphere/2012/04/partially-powered-off-vapp-vms.html#more
BR,
DanB
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.
im trying to update my news feed on facebook. Im using the new graph api. I can connect to graph, but when i try to publish some content to the feed object, nothing happens.
here´s my code:
<?php
$token = "xxxx";
$fields = "message=test&access_token=$token";
$c = curl_init("http://graph.facebook.com/me/feed");
curl_setopt($c,"CURLOPT_POST", true);
curl_setopt($c,"CURLOPT_POSTFIELDS",$fields);
$r = curl_exec($c);
print_r($r);
this returns:
{"error":{"type":"QueryParseException","message":"An active access token must be used to query information about the current user."}}1
then I try to pass access_token via GET:
$c = curl_init("http://graph.facebook.com/me/feed?access_token=$token");
this returns:
{"data":[]}1
Am I doing something wrong?
thanks
I found my error!
I was putting CURL options as a string rather than constants.
oopps...