Following tutorial shows how to display data as HTML based on that I just need to show response of XML as opposed to parsing it. I have tried to find solution but didn't have any luck. Any help will be appreciated.
<?php
$endpoint = 'http://svcs.ebay.com/services/search/FindingService/v1'; // URL to call
$query = 'iphone'; // Supply your own query keywords as needed
// Construct the findItemsByKeywords POST call
// Load the call and capture the response returned by the eBay API
// The constructCallAndGetResponse function is defined below
$resp = simplexml_load_string(constructPostCallAndGetResponse($endpoint, $query));
// Check to see if the call was successful, else print an error
if ($resp->ack == "Success") {
$results = ''; // Initialize the $results variable
// Parse the desired information from the response
foreach($resp->searchResult->item as $item) {
$link = $item->viewItemURL;
$title = $item->title;
// Build the desired HTML code for each searchResult.item node and append it to $results
$results .= "<tr><td><img src=\"$pic\"></td><td>$title</td></tr>";
}
}
else { // If the response does not indicate 'Success,' print an error
$results = "<h3>Oops! The request was not successful";
$results .= "AppID for the Production environment.</h3>";
}
function constructPostCallAndGetResponse($endpoint, $query) {
global $xmlrequest;
// Create the XML request to be POSTed
$xmlrequest = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n";
$xmlrequest .= "<findItemsByKeywordsRequest
xmlns=\"http://www.ebay.com/marketplace/search/v1/services\">\n";
$xmlrequest .= "<keywords>";
$xmlrequest .= $query;
$xmlrequest .= "</keywords>\n";
$xmlrequest .= "<paginationInput>\n
<entriesPerPage>3</entriesPerPage>\n</paginationInput>\n";
$xmlrequest .= "</findItemsByKeywordsRequest>";
// Set up the HTTP headers
$headers = array(
'X-EBAY-SOA-OPERATION-NAME: findItemsByKeywords',
'X-EBAY-SOA-SERVICE-VERSION: 1.3.0',
'X-EBAY-SOA-REQUEST-DATA-FORMAT: XML',
'X-EBAY-SOA-GLOBAL-ID: EBAY-GB',
'X-EBAY-SOA-SECURITY-APPNAME: ******',
'Content-Type: text/xml;charset=utf-8',
);
$session = curl_init($endpoint); // create a curl session
curl_setopt($session, CURLOPT_POST, true); // POST request type
curl_setopt($session, CURLOPT_HTTPHEADER, $headers); // set headers using $headers
array
curl_setopt($session, CURLOPT_POSTFIELDS, $xmlrequest); // set the body of the POST
curl_setopt($session, CURLOPT_RETURNTRANSFER, true); //
$responsexml = curl_exec($session); // send the request
curl_close($session); // close the session
return $responsexml; // returns a string
} // End of constructPostCallAndGetResponse function
?>
Try changing this (wrapped for clarity):
$resp = simplexml_load_string(
constructPostCallAndGetResponse($endpoint, $query)
);
to this:
$xmlString = constructPostCallAndGetResponse($endpoint, $query);
$resp = simplexml_load_string($xmlString);
// Now you have your raw XML to play with
echo htmlentities($xmlString);
// The XML document $resp is available too, if you wish to do
// something with that
The original feeds the XML response immediately into an XML parser, and creates an XML object with it (look up SimpleXML in the PHP manual for details). Here, we've split the two calls up, so the XML string is now saved in an intermediate variable.
Related
I am using Fat Secret API in my project and want to find the food names on search so I hard coded the food name say : banana and it is giving me error
8 Invalid signature: oauth_signature 'NECnoAOp6D2qLCg7YQ84fYyJYRE='
Below is my code
$consumer_key = "bcd69xxxxxxxxxxxxxxxxxxxxxxx52";
$secret_key = "62fe9xxxxxxxxxxxxxxxxxxxxxxxx54d";
$base = rawurlencode("GET")."&";
$base .= "http%3A%2F%2Fplatform.fatsecret.com%2Frest%2Fserver.api&";
$params = "format=json&";
$params = "method=foods.search&";
$params .= "oauth_consumer_key=$consumer_key&";
$params .= "oauth_nonce=".uniqid()."&";
$params .= "oauth_signature_method=HMAC-SHA1&";
$params .= "oauth_timestamp=".time()."&";
$params .= "oauth_version=1.0&";
$params .= "search_expression=banana";
$params .= "oauth_callback=oob";
$params2 = rawurlencode($params);
$base .= $params2;
//encrypt it!
$sig= base64_encode(hash_hmac('sha1', $base, "62fe9d66898545a0b48d497a4394054d&", true));
$url = "http://platform.fatsecret.com/rest/server.api?".$params."&oauth_signature=".rawurlencode($sig);
//$food_feed = file_get_contents($url);
list($output,$error,$info) = loadFoods($url);
echo '<pre>';
if($error == 0){
if($info['http_code'] == '200'){
echo $output;
} else {
die('Status INFO : '.$info['http_code']);
}
}else{
die('Status ERROR : '.$error);
}
function loadFoods($url)
{
// create curl resource
$ch = curl_init();
// set url
curl_setopt($ch, CURLOPT_URL, $url);
//return the transfer as a string
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
// $output contains the output string
$output = curl_exec($ch);
$error = curl_error($ch);
$info = curl_getinfo($ch);
// close curl resource to free up system resources
curl_close($ch);
return array($output,$error,$info);
}
Please Help me in this. I am new in OAuth and Fat Secret API, Please do share the necessary information if you know.
Thanks
I would like to write messenger bot based on this script:
<?php
$challenge = $_REQUEST['hub_challenge'];
$verify_token = $_REQUEST['hub_verify_token'];
// Set this Verify Token Value on your Facebook App
if ($verify_token === 'testtoken') {
echo $challenge;
}
$input = json_decode(file_get_contents('php://input'), true);
// Get the Senders Graph ID
$sender = $input['entry'][0]['messaging'][0]['sender']['id'];
// Get the returned message
$message = $input['entry'][0]['messaging'][0]['message']['text'];
//API Url and Access Token, generate this token value on your Facebook App Page
$url = 'https://graph.facebook.com/v2.6/me/messages?access_token=<ACCESS-TOKEN-VALUE>';
//Initiate cURL.
$ch = curl_init($url);
//The JSON data.
$jsonData = '{
"recipient":{
"id":"' . $sender . '"
},
"message":{
"text":"The message you want to return"
}
}';
//Tell cURL that we want to send a POST request.
curl_setopt($ch, CURLOPT_POST, 1);
//Attach our encoded JSON string to the POST fields.
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);
//Set the content type to application/json
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
//Execute the request but first check if the message is not empty.
if(!empty($input['entry'][0]['messaging'][0]['message'])){
$result = curl_exec($ch);
}
?>
All works correctly but i receive two responses to variable $message, for example:
Send "Hello";
$message = "Hello";
Receive message: "Hi";
$message = "Hi";
I would like to skip 3 and 4 points and receive only "Hello" message because i have to check if $message is my question or answer. Is it possible?
Greetings
You should skip any read and delivery messages, like this:
if (!empty($input['entry'][0]['messaging'])) {
foreach ($input['entry'][0]['messaging'] as $message) {
// Skipping delivery messages
if (!empty($message['delivery'])) {
continue;
}
// Skipping read messages
if (!empty($message['read'])) {
continue;
}
}
}
Or, you can deselect message_reads & message_deliveries checkboxes in Page Subscription section of your Facebook Page Settings/Webhooks.
Bear with my inexperience here, but can anyone point me in the right direction for how I can change the PHP script below to output each variable that is parsed from the XML file (title, link, description, etc) as a POST method instead of just to an HTML page?
<?php
$html = "";
$url = "http://api.brightcove.com/services/library?command=search_videos&any=tag:SMGV&output=mrss&media_delivery=http&sort_by=CREATION_DATE:DESC&token= // this is where the API token goes";
$xml = simplexml_load_file($url);
$namespaces = $xml->getNamespaces(true); // get namespaces
for($i = 0; $i < 80; $i++){
$title = $xml->channel->item[$i]->video;
$link = $xml->channel->item[$i]->link;
$title = $xml->channel->item[$i]->title;
$pubDate = $xml->channel->item[$i]->pubDate;
$description = $xml->channel->item[$i]->description;
$titleid = $xml->channel->item[$i]->children($namespaces['bc'])->titleid;
$html .= "<h3>$title</h3>$description<p>$pubDate<p>$link<p>Video ID: $titleid<p>
<iframe width='480' height='270' src='http://link.brightcove.com/services/player/bcpid3742068445001?bckey=AQ~~,AAAABvaL8JE~,ufBHq_I6FnyLyOQ_A4z2-khuauywyA6P&bctid=$titleid&autoStart=false' frameborder='0'></iframe><hr/>";/* this embed code is from the youtube iframe embed code format but is actually using the embedded Ooyala player embedded on the Campus Insiders page. I replaced any specific guid (aka video ID) numbers with the "$guid" variable while keeping the Campus Insider Ooyala publisher ID, "eb3......fad" */
}
echo $html;
?>
#V.Radev Here's another PHP script using cURL that I think will work with the API I'm trying to send data to:
<?PHP
$url = 'http://api.brightcove.com/services/post';
//open connection
$ch = curl_init($url);
//set the url, number of POST vars, POST data
curl_setopt($ch,CURLOPT_POST, 1);
curl_setopt($ch,CURLOPT_POSTFIELDS, '$title,$descripton,$url' . stripslashes($_POST['$title,$description,$url']));
curl_setopt($ch,CURLOPT_RETURNTRANSFER, true);
// Enable for Charles debugging
//curl_setopt($ch,CURLOPT_PROXY, '127.0.0.1:8888');
$result = curl_exec($ch);
curl_close($ch);
print $result;
?>
My question is, how can I pass the variables from my feed parsing script (title, description, URL) to this new script?
I have this code from Brightcove, can I just output the variables from my parser script and send to this PHP script so that the data goes to the API?
<?php
// This code example uses the PHP Media API wrapper
// For the PHP Media API wrapper, visit http://docs.brightcove.com/en/video-cloud/open-source/index.html
// Include the BCMAPI Wrapper
require('bc-mapi.php');
// Instantiate the class, passing it our Brightcove API tokens (read, then write)
$bc = new BCMAPI(
'[[READ_TOKEN]]',
'[[WRITE_TOKEN]]'
);
// Create an array of meta data from our form fields
$metaData = array(
'name' => $_POST['bcVideoName'],
'shortDescription' => $_POST['bcShortDescription']
);
// Move the file out of 'tmp', or rename
rename($_FILES['videoFile']['tmp_name'], '/tmp/' . $_FILES['videoFile']['name']);
$file = '/tmp/' . $_FILES['videoFile']['name'];
// Create a try/catch
try {
// Upload the video and save the video ID
$id = $bc->createMedia('video', $file, $metaData);
echo 'New video id: ';
echo $id;
} catch(Exception $error) {
// Handle our error
echo $error;
die();
}
?>
Post is a request method to access a specific page or resource. With echo you are sending data which means that you are responding. In this page you can only add response headers and access it with a request method such as post, get, put etc.
Edit for API request as mentiond in the comments:
$curl = curl_init('your api url');
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $your_data_to_send);
$result_from_api = curl_exec($curl);
curl_close($curl);
I'm trying to retrieve data from Twitter by connecting to twitter API and make some requests the my code below but I get nothing in return... I just requested the bearer token and successfully received it.
This is the code in PHP:
$url = "https://api.twitter.com/1.1/statuses/user_timeline.json?
count=10&screen_name=twitterapi";
$headers = array(
"GET".$url." HTTP/1.1",
"Host: api.twitter.com",
"User-Agent: My Twitter App v1.0.23",
"Authorization: Bearer ".$bearer_token."",
"Content-Type: application/x-www-form-urlencoded;charset=UTF-8",
);
$ch = curl_init(); // setup a curl
curl_setopt($ch, CURLOPT_URL,$url); // set url to send to
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); // set custom headers
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // return output
$retrievedhtml = curl_exec ($ch); // execute the curl
print_r($retrievedhtml);
when using the print_r nothing is shown at all and when using the var_dump i find "bool(false)"
Any idea with what could be wrong with this?
Regards,
Try outputting any potential cURL errors with
curl_error($ch);
after the curl_exec command. That might give you a clue about what's going wrong. Completely empty responses usually point to something going wrong with the cURL operation itself.
Your headers are wrong... do not include
"GET".$url." HTTP/1.1"
in your headers.
Further, you may print out the HTTP return code by
$info = curl_getinfo($ch);
echo $info["http_code"];
200 is success, anything in the 4xx or 5xx range means something went wrong.
I built based on comments I found in a Twitter dev discussion by #kiers. Hope this helps!
<?php
// Get Token
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL, 'https://api.twitter.com/oauth2/token');
curl_setopt($ch,CURLOPT_POST, true);
$data = array();
$data['grant_type'] = "client_credentials";
curl_setopt($ch,CURLOPT_POSTFIELDS, $data);
$screen_name = 'ScreenName'; // add screen name here
$count = 'HowManyTweets'; // add number of tweets here
$consumerKey = 'EnterYourTwitterAppKey'; //add your app key
$consumerSecret = 'EnterYourTwitterAppSecret'; //add your app secret
curl_setopt($ch,CURLOPT_USERPWD, $consumerKey . ':' . $consumerSecret);
curl_setopt($ch,CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
curl_close($ch);
$bearer_token = json_decode($result);
$bearer = $bearer_token->{'access_token'}; // this is your app token
// Get Tweets
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL, 'https://api.twitter.com/1.1/statuses/user_timeline.json?count='.$count.'&screen_name='.$screen_name);
curl_setopt($ch,CURLOPT_HTTPHEADER,array('Authorization: Bearer ' . $bearer));
curl_setopt($ch,CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
curl_close($ch);
$cleanresults = json_decode($result);
// Release the Kraken!
echo '<ul id="twitter_update_list">';
foreach ( $cleanresults as $tweet ) {
// Set up some variables
$tweet_url = 'http://twitter.com/'.$screen_name.'/statuses/'.$tweet->id_str; // tweet url
$urls = $tweet->entities->urls; // links
$retweet = $tweet->retweeted_status->user->screen_name; // there is a retweeted user
$time = new DateTime($tweet->created_at); // lets grab the date
$date = date_format($time, 'M j, g:ia'); // and format it accordingly
$url_find = array();
$url_links = array();
if ( $urls ) {
if ( !is_array( $urls ) ) {
$urls = array();
}
foreach ( $urls as $url ) {
$theurl = $url->url;
if ( $theurl ) {
$url_block = ''.$theurl.'';
$url_find[] = $theurl; // make array of urls
$url_links[] = $url_block; // make array of replacement link blocks for urls in text
}
}
}
if ( $retweet ) { // add a class for retweets
$link_class = ' class="retweet"';
} else {
$link_class = '';
}
echo '<li'.$link_class.'>';
$new_text = preg_replace('##([\\d\\w]+)#', '$0', $tweet->text); // replace all #mentions with actual links
$newer_text = preg_replace('/#([\\d\\w]+)/', '$0', $new_text); // replace all #tags with actual links
$text = str_replace( $url_find, $url_links, $newer_text); // replace all links with actual links
echo $text;
echo '<br /><a class="twt-date" href="'.$tweet_url.'" target="_blank">'.$date.'</a>'; // format the date above
echo '</li>';
}
echo '</ul>';
I put together some files on github, named "Flip the Bird." Hope this helps...
I created PHP library supporting application-only authentication and single-user OAuth. https://github.com/vojant/Twitter-php.
Usage
$twitter = new \TwitterPhp\RestApi($consumerKey,$consumerSecret);
$connection = $twitter->connectAsApplication();
$data = $connection->get('/statuses/user_timeline',array('screen_name' => 'TechCrunch'));
code is as below:
<?php
//set up variables
$theData = '<?xml version="1.0"?>
<note>
<to>php.net</to>
<from>lymber</from>
<heading>php http request</heading>
<body>i love php!</body>
</note>';
$url = 'http://www.example.com/script.php';
//create the httprequest object
$httpRequest_OBJ = new httpRequest($url, HTTP_METH_POST, $options);
//add the content type
$httpRequest_OBJ->setContentType = 'Content-Type: text/xml';
//add the raw post data
$httpRequest_OBJ->setRawPostData ($theData);
//send the http request
$result = $httpRequest_OBJ->send();
//print out the result
echo "<pre>"; print_r($result); echo "</pre>";
?>
Now httprequest calls the script here:
http://www.example.com/script.php
Over there I want to access the object, so that I can manipulate the data and send it back:
$httpRequest_OBJ->setRawPostData ($theData);
but it does not work. I tried $_POST['theData'], but this only works if you use $r->**addPostFields**(array('user' => 'mike', 'pass' => 's3c|r3t'));
How can I access the object $theData?
Thanks.
I think what you are after is php://input
So you can get the whole lot of XML that you posted like this:
$fp = fopen('php://input','r');
$data = '';
while (!feof($fp)) $data .= fread($fp,1024);
// $data should now contain the XML posted in your example
As a side note, I think the line
$httpRequest_OBJ->setContentType = 'Content-Type: text/xml';
...should probably just read
$httpRequest_OBJ->setContentType = 'text/xml';